How is the sink function used in the R language?
In R language, the sink() function is used to redirect output, writing the output from the console to a file. It has two commonly used uses:
- Write the output from the console to a file.
sink("output.txt")
print("Hello, world!")
sink()
The above code writes the output on the console to a file named output.txt. When the sink() function is executed, the output will be restored to the console.
- Write the output on the console to both a file and the console simultaneously.
sink("output.txt", append=TRUE)
print("Hello, world!")
sink()
The above code will write the output from the console to both the output.txt file and the console. Setting the append=TRUE parameter will append the content to the file instead of overwriting it.