代码之家  ›  专栏  ›  技术社区  ›  Joshua Rosenberg Choens

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

r
  •  12
  • Joshua Rosenberg Choens  · 技术社区  · 7 年前

    我试图从打印输出的函数中获取输出 打印到控制台。

    这个 capture.output 建议在中使用函数 some answers ,但我不清楚如何捕获输出,但仍然返回函数的输出。

    E、 g.,如果我有功能 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() ),但使用它们的答案不使用函数(因此我很难应用这种方法)。

    1 回复  |  直到 7 年前
        1
  •  18
  •   G. Grothendieck    7 年前

    按如下方式分配函数的输出:

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