将glm模型传递给自定义函数

Passing glm model to self-defined function

我想将 glm 模型传递给自定义函数,但 运行 进入错误消息

Error in eval(expr, envir, enclos) : object ... not found

我想通过拟合的 glm 模型并使用相同的公式、族、数据和权重作为输入来拟合新模型。我已经尝试使用下面的代码(如果我只是手动设置 glmModel = testModel 和 运行 函数中的代码,它就可以正常工作)。出了什么问题?

glmPassing <- function(glmModel){
   weightsTest = glmModel$weights
   glmTest = glm(formula = glmModel$formula, family = glmModel$family, data = glmModel$data, weights = weightsTest)
   summary(glmTest)
} 

test = iris
testModel = glm(Sepal.Length ~ Sepal.Width + I(Sepal.Width^2), family = gaussian, data = test, weights = Petal.Width)
glmPassing(testModel) 

我已将权重分离到一个新变量,因为我发现这是导致错误消息的原因。使用上面的代码,错误消息是

Error in eval(expr, envir, enclos) : object 'weightsTest' not found

谢谢!

使用这个

glmPassing <- function(glmModel){
 weightsTest = glmModel$weights
 glmTest = do.call("glm", list(formula = glmModel$formula, family = glmModel$family, data = quote(glmModel$data), weights = weightsTest))
 summary(glmTest)
 }

总的来说,do.call功能有助于解决环境问题。

I am implementing my own cross-validation. The above example is very condensed to illustrate the problem and just tries to redo the exact same glm analysis. Thanks for getting involved (it's been answered).

谢谢。但正如 Flick 先生所提到的,我也认为 update() 是执行此操作的便利设施。 boot 包中的 cv.glm() 函数只是用它来做交叉验证。