Ad

R: Create A Linear Mixed-effect Model Loop That Removes One Fixed Independent Variable, Then Adds It Back In And Removes Another

- 1 answer

I'm looking for a way to create a linear mixed-effect model loop that removes one fixed effect independent variable, runs the model, adds it back in, and removes another fixed independent variable from the model.

For example:

library(lme4)

L1 <- lmer(cyl ~ disp + hp + mpg (carb|gear), mtcars)

How can I create a loop of this model so that each new regression loop iteration removes a single fixed effect independent variable, adds it back in on the next iteration, and removes a different fixed independent variable?

Doing this would produce these models:

Original full model: lmer(cyl ~ disp + mpg + (carb|gear), mtcars)

Partial model with mpg removed: lmer(cyl ~ disp + hp + (carb|gear), mtcars)

Partial model with mpg re-added and disp removed: lmer(cyl ~ hp + mpg (carb|gear), mtcars)

Partial model with disp re-added and hp removed: lmer(cyl ~ disp + mpg (carb|gear), mtcars)

I am also curious how I can add each model to a list after each loop iteration.

Thanks a lot!

Ad

Answer

Map over the fixed variables constructing the formula, fo, using reformulate and run lmer. This will produce a named list of "lmerMod" objects, one for each component of fixed such that that model omits that component. The full model will have an empty name.

library(lme4)

fixed <- c("", "disp", "hp", "mpg")

f <- function(v) {
  fo <- reformulate(c(setdiff(fixed, v), "(carb | gear)"), "cyl")
  cat("Running", format(fo), "\n")
  lmer(fo, data = mtcars)
}
out <- Map(f, fixed)
## Running cyl ~ disp + hp + mpg + (carb | gear) 
## boundary (singular) fit: see ?isSingular
## Running cyl ~ hp + mpg + (carb | gear) 
## Running cyl ~ disp + mpg + (carb | gear) 
## boundary (singular) fit: see ?isSingular
## Running cyl ~ disp + hp + (carb | gear) 
Ad
source: stackoverflow.com
Ad