Unexpected error when looping the glmer function with the effects package

Viewed 161

I am trying to pass the effect function from the effects package together with a (gl)merMod object from the lme4 package through a lapply loop and encounter an error I do not expect. It seems that the effect function fails to look for objects inside the loop. What do I do wrong and how to get the loop working without manually placing the data frame into the workspace?

library(lme4)
library(reshape2)
library(effects)

dat <- data.frame(var = rep(c("A", "B", "C"), 100), treat = rep(c("T1", "T2"),
each = 150), rand =  rep(c("B", "C", "A"), 100), value = rep(c(1,0), 150))

lapply(levels(dat$treat), function(k) {
  y <- subset(dat, treat == k)
  mod <- glmer(value ~ var + (1|rand), data = y, family = binomial)
  })
## Works

lapply(levels(dat$treat), function(k) {
  y <- subset(dat, treat == k)
  mod <- glmer(value ~ var + (1|rand), data = y, family = binomial)
  effects::effect("var", mod)
})
## Error in is.data.frame(data) : object 'y' not found

y <- subset(dat, treat == "T1")
mod <- glmer(value ~ var + (1|rand), data = y, family = binomial)
effects::effect("var", mod)
## Works

lapply(levels(dat$treat), function(k) {
  y <- subset(dat, treat == k)
  mod <- glmer(value ~ var + (1|rand), data = y, family = binomial)
  effects::effect("var", mod)
})
## Works, because object y is in the workspace
1 Answers

I had a similar problem (using lm with a model.matrix) where effects worked fine on its own, but then not did not work in my lapply loop.

I tried rewriting my code with a for loop instead which solved my problem. Since the for loop assigns objects to the global environment each time, you would not have to place them there manually.

With your example, the for loop does not throw an error, although now you will need to assign the output to something:

for(k in levels(dat$treat)) {
  y <- subset(dat, treat == k)
  mod <- glmer(value ~ var + (1|rand), data = y, family = binomial)
  effects::effect("var", mod)
  }
Related