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

Jos*_*erg 5 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\""
Run Code Online (Sandbox Code Playgroud)

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

G. *_*eck 5

像这样分配函数的输出:

capture <- capture.output(result <- f()); result
## [1] "value"
Run Code Online (Sandbox Code Playgroud)

  • 您也可以将整个内容包装在 `invisible` 中,而不是分配给一个值 `invisible(capture.output(result &lt;- f()))` (2认同)