我正在尝试从打印输出不打印到控制台的功能输出.
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()),但使用它们的答案不使用函数(因此我在应用该方法时遇到困难).
像这样分配函数的输出:
capture <- capture.output(result <- f()); result
## [1] "value"
Run Code Online (Sandbox Code Playgroud)