I want to pass a glm model to a self-defined function but run into the error message
Error in eval(expr, envir, enclos) : object ... not found
I want to pass the fitted glm model and use the same formula, family, data and weights as the input to fit a new model. I have tried with the code below (which works fine if I just set glmModel = testModel
and run the code within the function manually). What goes wrong?
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)
I have separated the weights to a new variable since I found out that's what causes the error message. With the code above the error message is
Error in eval(expr, envir, enclos) : object 'weightsTest' not found
Thank you!
Use this
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)
}
In general, the do.call
function is helpful to get rid of environment issues.
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).
Thanks. But as Mr. Flick mentioned, I also think update()
is a convenient facility to do this. The cv.glm()
function from boot
package is just using it for doing cross-validation.