In the R scripting language, how do I write lines of text, e.g. the following two lines
Hello World to a file named "output.txt"?
In the R scripting language, how do I write lines of text, e.g. the following two lines
Hello World to a file named "output.txt"?
fileConn Actually you can do it with sink():
sink("outfile.txt") cat("hello") cat("\n") cat("world") sink() hence do:
file.show("outfile.txt") # hello # world I would use the cat() command as in this example:
> cat("Hello",file="outfile.txt",sep="\n") > cat("World",file="outfile.txt",append=TRUE) You can then view the results from with R with
> file.show("outfile.txt") hello world What's about a simple writeLines()?
txt or
txt 1.Using file argument in cat.
cat("Hello World", file="filename") 2.Use sink function to redirect all output from both print and cat to file.
sink("filename") # Begin writing output to file print("Hello World") sink() # Resume writing output to console NOTE: The print function cannot redirect its output, but the sink function can force all output to a file.
3.Making connection to a file and writing.
con You could do that in a single statement
cat("hello","world",file="output.txt",sep="\n",append=TRUE) To round out the possibilities, you can use writeLines() with sink(), if you want:
> sink("tempsink", type="output") > writeLines("Hello\nWorld") > sink() > file.show("tempsink", delete.file=TRUE) Hello World To me, it always seems most intuitive to use print(), but if you do that the output won't be what you want:
... > print("Hello\nWorld") ... [1] "Hello\nWorld" Based on the best answer:
file Note that the yourObject needs to be in a string format; use as.character() to convert if you need.
But this is too much typing for every save attempt. Let's create a snippet in RStudio.
In Global Options >> Code >> Snippet, type this:
snippet wfile file Then, during coding, type wfile and press Tab.
ptf ",sep = "",collapse = NULL),outFile))} #Prints txtToPrint to outFile in cwd. #!/bin/bash echo txtToPrint > outFile