Reputation: 11
Lets say I want to use sink for writing to a file in R.
sink("outfile.txt")
cat("Line one.\n")
cat("Line two.")
sink()
question 1. I have seen people writing sink() at the end, why do we need this? Can something go wrong when we do not have this?
question 2. What is the best way to write many lines one by one to file with a for-loop, where you also need to format each line? That is I might need to have different number in each line, like in python I would use outfile.write("Line with number %.3f",1.231) etc.
Upvotes: 1
Views: 1146
Reputation: 10543
Question 1:
The sink
function redirects all text going to the stdout
stream to the file handler you give to sink
. This means that anything that would normally print out into your interactive R session, will now instead be written to the file in sink, in this case "outfile.txt".
When you call sink
again without any arguments you are telling it to resume using stdout
instead of "outfile.txt". So no, nothing will go wrong if you don't call sink()
at the end, but you need to use it if you want to start seeing output again in your R session/
As @Roman has pointed out though, it is better to explicitly tell cat
to output to the file. That way you get only what you want, and expect to see in the file, while still getting the rest ouf the output in the R session.
Question 2:
This also answers question two. R (as far as I am aware) does not have direct file handling like in python
. Instead you can just use cat(..., file="outfile.txt")
inside a for loop.
Upvotes: 3