作为变量R通函数 [英] R pass function in as variable

查看:139
本文介绍了作为变量R通函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个项目来分析函数的工作输出,因此需要在传递函数为R.参数为了澄清,我有不同数量的模型,不是找援助上建立模型,只是通过在模型函数名到计分函数。

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)
}

我可以调用这个code。与有效的Y和X垫以

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])

这是我与上述code得到的错误是

The error that I get with the above code is

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

我与as.function()和上市unlisting的ARGS发挥各地,但没有任何工程。例如下面的所有ARGS都呈现相同的错误如上

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.

推荐答案

match.fun 是你的朋友。它是什么适用 tapply 等人使用了同样的目的。请注意,如果您需要将参数传递给模型拟合函数,那么你要么需要所有这些捆绑起来成为像这样函数(x)的总和(X == 0,na.rm =功能TRUE)或者提供它们作为一个列表,并使用 do.call 像这样 do.call(MYFUNC,funcargs)

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).

希望这有助于。

这篇关于作为变量R通函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆