is it possible to redirect console output to a variable?

后端 未结 2 2059
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 05:27

In R, I\'m wondering if it\'s possible to temporarily redirect the output of the console to a variable?

p.s. There are a few examples on the web on how to use

2条回答
  •  盖世英雄少女心
    2020-11-30 06:14

    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).

提交回复
热议问题