Home > Back-end >  R: Create a linear mixed-effect model loop that removes one fixed independent variable, then adds it
R: Create a linear mixed-effect model loop that removes one fixed independent variable, then adds it

Time:02-10

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!

CodePudding user response:

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) 

CodePudding user response:

Check out the MuMIn package for model averaging. You normally start by running the full model, and the dredge function can be used to iteratively run models with all combinations of predictors. You can specify effects that you want to keep consistent e.g. your (carb|gear) random effect. The outputs can give you a table of results for each model.

  • Related