Avoid the problem entirely
This problem can be avoided through the use of the 'on.exit' function:
sink("output.txt")
on.exit(sink())
my_function_that_might_error()
Explanation
The most common time I experience this is when an error occurs preventing a sink from closing. For example, the following will leave an open sink after execution.
sink("output.txt")
my_function_that_will_error()
sink()
This can be avoided using on.exit(sink())
. This will close the sink "when the current function exits (either naturally or as the result of an error)" (documentation here).
But you do have to change the order:
sink("output.txt")
on.exit(sink())
my_function_that_might_error()
So we create the sink, tell R to close it when it exits, and then execute the code that might error. This will close the sink regardless of whether the code errors or not.
Limitations
Note that the behaviour of on.exit
may not work as expected when running interactively. If the line on.exit(sink())
is run at the console, it triggers immediately as all of the current commands have concluded.
Hence, this approach requires either sourcing a script or the sink being created and closed within some R function/process.
See the documentation for on.exit
for more information.