R pass function in as variable

another response:

models = list(model1)
scoreModel1 = score(df$y,df$x,models[[1]])

Example to pass function in as variable:

f_add<- function(x,y){ x + y }
f_subtract<- function(x,y){ x - y }
f_multi<- function(x,y){ x * y }

operation<- function(FUN, x, y){ FUN(x , y)}

operation(f_add, 9,2)
#> [1] 11
operation(f_subtract, 17,5)
#> [1] 12
operation(f_multi,6,8)
#> [1] 48

good luck


match.fun is your friend. It is what apply tapply et al use for the same purpose. Note that if you need to pass arguments to the model fitting functions then you will either need to bundle all of these up into a function like so function(x) sum(x==0, na.rm=TRUE) or else supply them as a list and use do.call like so do.call(myfunc, funcargs).

Hope this helps.


For anyone arriving here from google wondering how to pass a function as an argument, here's a great example:

randomise <- function(f) f(runif(1e3))
 
randomise(mean)
#> [1] 0.5029048 

randomise(sum)
#> [1] 504.245

It's from Hadley's book found here


your list objects can simply be the functions directly. Maybe you can get some use out of this structure, or else take Roland's advice and pass formulas. Richiemorrisroe's answer is probably cleaner.

fun1 <- function(x,y){
    x+y
}

fun2 <- function(x,y){
    x^y
}

fun3 <- function(x,y){
    x*y
}

models <- list(fun1 = fun1, fun2 = fun2, fun3 = fun3)

models[["fun1"]](1,2)
 [1] 3
models[[1]](1,2)
 [1] 3

lapply(models, function(FUN, x, y){ FUN(x = 1, y = 2)})
$fun1
 [1] 3

$fun2
 [1] 1

$fun3
 [1] 2