是否可以将控制台输出重定向到变量? [英] is it possible to redirect console output to a variable?

查看:111
本文介绍了是否可以将控制台输出重定向到变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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()是:

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:


与下沉相关,就像 with与 attach相关。 p>

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

...这表明 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).

这篇关于是否可以将控制台输出重定向到变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆