2

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:

  1. Using writeLines():
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
  1. Using sink():
sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()
  1. 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:

  1. Are there situations when one method is better than the others?
  2. 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.

Richard Erickson
  • 2,520
  • 8
  • 26
  • 36
  • 1
    This is an interesting question, but think it could go off in many tangents. Do you have any more info about your intended use-case or some direction for answering the questions? For instance, `sink()` is inherently different in my opinion, because it diverts output from the console. `writeLines()` seems like the best option for dealing with a lot of text... and so on. – Matt Jun 02 '22 at 18:19
  • Not an answer, but `capture.output(cat("Hello\nWorld\n"), file="outfile.txt")` is a fourth option. – dcarlson Jun 02 '22 at 18:22
  • @Matt `because it diverts output from the console` is part of an answer I'm looking for. I could not find any broad R documentation about why to use one function over another. – Richard Erickson Jun 02 '22 at 18:29

0 Answers0