问题描述
在R中,我想知道是否可以临时将控制台的输出重定向到一个变量?
In R, I'm wondering if it's possible to temporarily redirect the output of the console to a variable?
p.s。在网上有几个例子,如何使用sink()将输出重定向到一个文件名,但没有一个我可以找到显示如何重定向到一个变量。
p.s. There are a few examples on the web on how to use sink() to redirect the output into a filename, but none that I could find showing how to redirect into a variable.
pps在实践中,这是有用的,因为我需要从R中的一些内置函数打印出一部分默认控制台输出。
p.p.s. The reason this is useful, in practice, is that I need to print out a portion of the default console output from some of the built in functions in R.
推荐答案
我相信结果< - capture.output(...)
是你需要的(即使用默认 file = NULL
参数)。 sink(textConnection(results)); ...; sink()
也应该工作,但是?capture.output
说, capture.output c $ c>是:
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:
...这表明 capture.output()
它是更包含的(即你不必记得终止 sink()
)。
... 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()
).
你想将多个语句的输出发送到一个变量,你可以用大括号括起来 {}
,但是如果块非常复杂,最好使用 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).
这篇关于在R中,是否可以将控制台输出重定向到变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!