Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R pass function in as variable

I am working on a project to profile function outputs so need to pass a function in as an argument in R. To clarify, I have a varying number of models, and am not looking for assistance on setting up the models, just passing in the model function names into the scoring function.

This works for a direct call, but I want to make it more generic for building out the module. Here is a brief example:

#create a test function:
model1 = function(y,X){
fit = lm(y~X)
output = data.frame(resid = fit$residuals)
}

#score function:
score = function(y,X,model){
y= as.matrix(y) 
X = as.matrix(X)
fitModel = model(y,X)
yhat = y - fitModel$residual
output = data.frame(yhat=yhat)
}

I can call this code with valid y and X mats with

df <- data.frame(x=rnorm(5),y=runif(5))
scoreModel1 = score(df$y,df$x,model1)

But what I am looking for is a method of listing all of the models, and looping through, and/or calling the score function in a generic way. For instance:

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

The error that I get with the above code is

Error in score(y, X, model) : 
could not find function "model"

I have played around with as.function(), and listing and unlisting the args, but nothing works. For instance all the following args have rendered the same error as above

models = c(model1)
models = list(model1)
models = list("model1")

Thank you in advance for your help.

like image 250
Jim Crozier Avatar asked Dec 26 '12 20:12

Jim Crozier


1 Answers

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

like image 191
stevec Avatar answered Oct 25 '22 06:10

stevec