How can I sink the output of certain code into a variable? I want that output to still go to the console.
I much prefer the sink
notation; I don't want to use capture.output
for two reasons:
I came up with the code below, but it's a bit complicated. Is there an easier solution?
fileName <- tempfile()
sink(fileName, split = TRUE)
...
sink()
out <- readChar(fileName, file.info(fileName)$size)
unlink(fileName)
Your code doesn't seem so bad, but you can streamline things a little bit by using a textConnection
:
sink(tt <- textConnection("results","w"),split=TRUE)
print(11:15)
## [1] 11 12 13 14 15
sink()
results
## [1] "[1] 11 12 13 14 15"
close(tt) ## clean up
The only thing to watch out for is that if you don't close the connection, results
will be have locked bindings (see ?textConnection
), which will mean that you can't e.g. assign a new value to it.
The output character vector has locked bindings (see ‘lockBinding’) until ‘close’ is called on the connection.
Alternatively, you don't have to wrap multiple statements into a function to get them into capture.output()
- you can use curly brackets {}
to make multiple statements into a single evaluated output ...
results <- capture.output(split=TRUE,{
print("hello")
print("goodbye")
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With