example for sink() function in r

The sink() function in R is used to redirect R output to a file, a connection or a function. This can be useful for capturing results, errors or warnings generated from R code for further processing or review.

Here's an example of how to use the sink() function to redirect R output to a file:

main.r
# Set the file path to save the output to
sink_file <- "output.txt"

# Open the sink to start redirecting output to the file
sink(file = sink_file)

# Generate some output
cat("The square root of 16 is", sqrt(16), "\n")
cat("The sum of 5 and 3 is", 5 + 3, "\n")

# Close the sink to stop redirecting output
sink()
314 chars
13 lines

After running the above code, the output generated from the cat() functions will be saved to a file called "output.txt" in the working directory.

In addition to files, sink() can also redirect output to a connection or a function by passing in a connection object or a function name as the file argument.

Note that when using sink(), it is important to remember to use sink() a second time, without an argument, to restore output back to the console when you are finished redirecting it. This is necessary because output redirection persists beyond the point where you no longer want it to apply, and this can cause unexpected issues if not handled properly.

gistlibby LogSnag