【问题标题】:Modify the return/print option of a custom function in r修改 r 中自定义函数的返回/打印选项
【发布时间】:2020-09-30 04:47:59
【问题描述】:

我构建了一个自定义函数,它打印类的输出及其概率(分类器),如下所示:

fun(formula, data)
> "Class" 0.5

我将此fun 集成到另一个函数new_fun,但我使用fun 的修改结果作为new_fun 的输出。因此,我不需要类和概率的fun 的原始输出。将原始输出集成到new_fun 后,有没有办法避免返回/打印?

【问题讨论】:

    标签: r function return-value func


    【解决方案1】:

    你可以使用capture.output:

    f <- function() {print("test"); "result"}
    g <- function() { capture.output(result<-f()); result}
    
    
    f()
    #> [1] "test"
    #> [1] "result"
    g()
    #> [1] "result"
    

    reprex package (v0.3.0) 于 2020 年 9 月 30 日创建

    在您提供的示例中,这将是:

    
    new_fun <- function(...){
      myformula <- ...
      mydata <- ...
    
      #Call to fun with captured output
      capture.output( funresult <- fun(myformula, mydata))
    
      #Process further funresult
      ...
      
    }
    

    【讨论】:

    • 我不确定如何在我的代码中实现这一点。我应该在哪里包含 { capture.output(result
    猜你喜欢
    • 2018-04-16
    • 2017-12-14
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    相关资源
    最近更新 更多