This question, Write lines of text to a file in R, shows three different for saving outputs to a plain text file. Using the example from the question, let's say that we want to create a file named output.txt
with this text:
Hello
World
The question's answers show three methods:
- Using
writeLines()
:
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
- Using
sink()
:
sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()
- Using
cat()
:
cat("Hello",file="outfile.txt",sep="\n")
cat("World",file="outfile.txt",append=TRUE)
Some of the answers and comments note that cat()
would be slower than the other two methods.
However, my questions are:
- Are there situations when one method is better than the others?
- If one method is more idiomatically correct or quicker than the other two methods in R, why?
I searched SO and only found the linked answer. I have found other why question on SO (e.g., Why is processing a sorted array faster than processing an unsorted array?) so I think this question is on topic for the site.