How to output / split / copy console output to a variable in R?

How can I sink the output of a certain code into a variable? I want this output to still be coming to the console.

I prefer the designation sink ; I do not want to use capture.output for two reasons:

  • This requires that the corresponding code be the only function; I don't want to complicate my code by creating functions to capture output
  • It does not allow the captured output to still go to the console.

I came up with the code below, but it is a bit complicated. Is there an easier solution?

 fileName <- tempfile() sink(fileName, split = TRUE) ... sink() out <- readChar(fileName, file.info(fileName)$size) unlink(fileName) 
+5
source share
1 answer

Your code doesn't look so bad, but you can simplify it a bit by using 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 you need to pay attention to is that if you do not close the connection, the results will have locked bindings (see ?textConnection ), which will mean that you cannot, for example. Assign it a new value.

The output character of the symbol has locked bindings (see "lockBinding") until "close" is called in the connection.

Alternatively, you do not need to include several statements in the function to get them in capture.output() - you can use curly braces {} to make several statements in the same output ...

 results <- capture.output(split=TRUE,{ print("hello") print("goodbye") }) 
+1
source

Source: https://habr.com/ru/post/1202312/


All Articles