Write lines of text to a file in R
Solution 1:
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
Solution 2:
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
Solution 3:
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
Solution 4:
What's about a simple writeLines()
?
txt <- "Hallo\nWorld"
writeLines(txt, "outfile.txt")
or
txt <- c("Hallo", "World")
writeLines(txt, "outfile.txt")
Solution 5:
You could do that in a single statement
cat("hello","world",file="output.txt",sep="\n",append=TRUE)