4

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.

3
  • 1
    Try sink("output.txt", type=c("output", "message"), append=TRUE) Commented Apr 30, 2015 at 16:19
  • 2
    I ran into this problem too: <stackoverflow.com/q/17710469/903061>. If you read ?cat, the append argument only matters if you're using the file argument of cat. Commented Apr 30, 2015 at 16:20
  • @RichardScriven: You're right! sink() has its own append and as you said I don't even need to use append as long as I do not call sink(NULL). Please post your answer. Thanks! Commented Apr 30, 2015 at 16:29

1 Answer 1

6

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.