Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tee/split/copy console output into variable in R?

Tags:

r

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:

  1. It requires the respective code to be a single function; I don't want to complicate my code by creating functions just to capture output
  2. It doesn't allow the captured output to still go to console.

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)
like image 375
Tomas Avatar asked Nov 10 '22 02:11

Tomas


1 Answers

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")
})
like image 123
Ben Bolker Avatar answered Nov 15 '22 06:11

Ben Bolker