简体   繁体   English

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

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

I'm trying to have output from a function that prints output not print to the console. 我正在尝试从打印输出打印到控制台的功能输出。

The capture.output function is recommended in some answers , but it's not clear to me how to capture the output but still return the function's output. 某些答案中建议使用capture.output函数,但我不清楚如何捕获输出但仍然返回函数的输出。

Eg, if I have function f() and want "printed output!" 例如,如果我有函数f()并想要"printed output!" to not print to the console but to have "value" be returned: 不打印到控制台但返回"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\""

I think the solution may involve using sink (and con() ), but the answer that uses them does not use a function (and so I'm having difficulty applying the approach). 我认为解决方案可能涉及使用sink (和con() ),但使用它们的答案不使用函数(因此我在应用该方法时遇到困难)。

Assign the output of the function like this: 像这样分配函数的输出:

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

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

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