rimorob
rimorob

Reputation: 644

step/stepAIC on glms constructed inside function calls

I'm having a problem linked to visibility/environment. In short, glms constructed inside functions can't be simplifed using step/stepAIC:

foo = function(model) {
  m = glm(y~x, family=model$family, data = dframe)
  return(m)
}

y = rbinom(100, 1, 0.5)
x = y*rnorm(100) + rnorm(100)
dframe = data.frame(y, x)
m = glm(y~x, family='binomial', data = dframe)
m2 = foo(m)
library(MASS)
summary(m2)
print(m2$family)
m3 = stepAIC(m2, k = 2)

This results in the following error:

Error in glm(formula = y ~ 1, family = model$family, data = dframe) : 
  object 'model' not found

This despite m2 looking like it fit well and the family is defined. Sorry if the example is a little contrived.

Upvotes: 1

Views: 119

Answers (1)

rimorob
rimorob

Reputation: 644

Found the solution - the original glm needs to be constructed with do.call.

foo = function(model) {
  form.1<-as.formula(y ~ x)
  dat = model$data
  fam = model$family
  m <- do.call("glm", list(form.1, data=dat, family=fam))
  ##m = glm(y~x, family='binomial', data = model$dframe)
  return(m)
}

y = rbinom(100, 1, 0.5)
x = y*rnorm(100) + rnorm(100)
dframe = data.frame(y, x)
m = glm(y~x, family='binomial', data = dframe)
m2 = foo(m)
library(MASS)
summary(m2)
print(m2$family)
m3 = stepAIC(m2, k = 2)

Upvotes: 1

Related Questions