繁体   English   中英

从R中捕获函数的打印输出(但仍然返回其值)

[英]Capture the printed output from a function (but still return its value) in R

我正在尝试从打印输出打印到控制台的功能输出。

某些答案中建议使用capture.output函数,但我不清楚如何捕获输出但仍然返回函数的输出。

例如,如果我有函数f()并想要"printed output!" 不打印到控制台但返回"value"

f <- function() {
    print("printed output!")
    return("value")
}

# printed output is returned - want to capture the output

f()
#> [1] "printed output!"
#> [1] "value"

# also doesn't work, as captured output and function's output is returned

capture.output(f())
#> [1] "[1] \"printed output!\"" "[1] \"value\""

我认为解决方案可能涉及使用sink (和con() ),但使用它们的答案不使用函数(因此我在应用该方法时遇到困难)。

像这样分配函数的输出:

capture <- capture.output(result <- f()); result
## [1] "value"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM