Search code examples
ruser-defined-functionssapply

How to pass an input parameter for a UDF to sapply


I have a vector of values and a user defined function with multiple parameters. I want to sapply my UDF to every value in this vector while every entry in this vector is also an input parameter for the UDF

t <- 1:5
myfunc <- function (setvar, var){
    return(setvar * var)
}

sapply(t, myfunc(setvar = 2), var = t)

So in this case the result I'd like would be:

2 4 6 8 10

Solution

  • You could do

    sapply(t, myfunc, setvar = 2)
    #[1]  2  4  6  8 10
    

    Or to understand what exactly you are passing use an anonymous function

    sapply(t, function(x) myfunc(2, x))
    

    Also t is a base function in R, so it is better to use some other name for your variables.