R 将函数作为变量传入 [英] R pass function in as variable

查看:25
本文介绍了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)
}

我可以使用有效的 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)

但我正在寻找的是一种列出所有模型、循环遍历和/或以通用方式调用 score 函数的方法.例如:

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"

我玩过 as.function(),列出和取消列出 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")

预先感谢您的帮助.

推荐答案

match.fun 是您的朋友.这是 apply tapply 等人用于相同目的的东西.请注意,如果您需要将参数传递给模型拟合函数,那么您需要将所有这些捆绑到一个函数中,例如 function(x) sum(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天全站免登陆