MTT
MTT

Reputation: 5263

Avoid overwriting a text file in R

I have the following simple R code:

sink("output.txt", type=c("output", "message"))
cat("Hello", append = TRUE)
cat("World", append = TRUE)
sink(NULL)

It just writes the R console into a text file. I want to put it in an R source file (".r") and run it multiple times. I want to have the output as follows:

file.show("output.txt")
Hello
World
Hello
World

If I run it two times, I now see:

Hello
World

It looks like it has been overwritten.

Upvotes: 4

Views: 1784

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

sink() has its own append argument. And as Gregor mentioned, append in cat() only works when file is used.

However, you don't need to use append at all if you put all the cat() calls between the sink() calls, as sink() will continue to append to the file until you call sink(NULL)

But for your case, I think you want to do something like this for your sink() chunk:

sink("output.txt", type=c("output", "message"), append = TRUE)
cat("Hello", "\n")
cat("World", "\n")
sink(NULL)

Or more simply,

sink("output.txt", type=c("output", "message"), append = TRUE)
cat("Hello", "World", sep = "\n")
sink(NULL)

Repeating this operation twice, we have created the file and appended to it

Hello
World
Hello
World

Upvotes: 6

Related Questions