Search code examples
ruser-defined-functionsapplyudfmultiple-arguments

R Code: using UDF with multiple arguments for apply function


My UDF:

testfn = function(x1, x2, x3){
if(x1 > 0){y = x1 + x2 + x3}
if(x1 < 0){y = x1 - x2 - x3}
return(y)
}

My Sample Test set:

test = cbind(rep(1,3),c(2,4,6),c(1,2,3))

Running of apply:

apply(test, 1, testfn, x1 = test[1], x2 = test[2], x3 = test[3])

This is the error I get:

Error in FUN(newX[, i], ...) : unused argument (newX[, i])

How should I be using the apply so that my UDF evaluates the test set row by row?

I'm expecting:

[1] 4 7 10

I provided a simplified generalized UDF because I need to utilize more complex UDFs.


Solution

  • You can accomplish the same thing by passing the function directly into the apply

    apply(test, 1, function(x) if(x[1] > 0) sum(x) else x[1] - x[2] - x[3])
    
    [1]  4  7 10
    

    If you want to use your UDF you need to modify it.

    testfn = function(mydf){
      if(mydf[1] > 0){y = mydf[1] + mydf[2] + mydf[3]}
      if(mydf[1] < 0){y = mydf[1] - mydf[2] - mydf[3]}
      return(y)
    }
    
    apply(test, 1, testfn)