Search code examples
rfunctionreturn-valuefunc

Modify the return/print option of a custom function in r


I built a custom function in which it prints an output of the class and it's probability (classifier), like the following:

fun(formula, data)
> "Class" 0.5

I integrate this fun into another function new_fun, but I use a modified result of fun as an output for new_fun. Therefore, I don't need to original output of fun of the class and probability. Is there a way to avoid returning/printing the original output once it's integrated into new_fun?


Solution

  • You could use capture.output:

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

    Created on 2020-09-30 by the reprex package (v0.3.0)

    In the example you provided, this would be:

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