is it possible to redirect console output to a variable?

爱⌒轻易说出口 提交于 2019-11-27 19:40:38

I believe results <- capture.output(...) is what you need (i.e. using the default file=NULL argument). sink(textConnection("results")); ...; sink() should work as well, but as ?capture.output says, capture.output() is:

Related to ‘sink’ in the same way that ‘with’ is related to ‘attach’.

... which suggests that capture.output() will generally be better since it is more contained (i.e. you don't have to remember to terminate the sink()).

If you want to send the output of multiple statements to a variable you can wrap them in curly brackets {}, but if the block is sufficiently complex it might be better to use sink() (or make your code more modular by wrapping it in functions).

For the record, it's indeed possible to store stdout in a variable with the help of a temorary connection without calling capture.output -- e.g. when you want to save both the results and stdout. Example:

  1. Prepare the variable for the diverted R output:

    > stdout <- vector('character')
    > con    <- textConnection('stdout', 'wr', local = TRUE)
    
  2. Divert the output:

    > sink(con)
    
  3. Do some stuff:

    > 1:10
    
  4. End the diversion:

    > sink()
    
  5. Close the temporary connection:

    > close(con)
    
  6. Check results:

    > stdout
    [1] " [1]  1  2  3  4  5  6  7  8  9 10"
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!