简体   繁体   中英

R: loop multiple independent variables through a mixed effect model

I'm looking to loop a number of independent variables through a mixed effect model. There are a couple of similar questions but nothing that quite works for me. An example using mtcars:

data(mtcars)
mtcars <- mtcars

t <- as.data.frame(seq(from = 10, to = 1000, by = 100))
names(t)[1] <- "return"
t <- as.data.frame(t(t))

#create some new variables to loop through
new <- cbind(mtcars$drat, t)
new2 <- 1-exp(-mtcars$drat/new[, 2:10])
new3 <- cbind(mtcars, new2)

xnam <- paste(colnames(mtcars)[c(3:4)], sep="") 
xnam2 <- paste(colnames(reference)[c(12:20)], sep="")

#basic model (works fine)
fmla <- paste(xnam, collapse= "+")
fla <- paste("cyl ~", paste(fmla))
f <- paste0(paste(fla), " +(carb|gear)")
mtcarsmodel <- lmer(f, data= mtcars)
mtcarsmodel

So with my 'basic' model, I now want iteratively run each of the variables in xnam2 through the model as a fixed effect, but can't get it working with lapply and paste method:

f2 <- " +(carb|gear)"

newmodels <- lapply(xnam2, function(x) {
  lmer(substitute(paste(fla), i + (paste(f2)), list(i = as.name(x))), data = mtcars)
})

So cyl ~ disp+hp + looping variable + (carb|gear) is what I'm after.

Hopefully that's clear with what I'm trying to accomplish. I'm getting a bit confused with the multiple pastes, but seems like the best way to approach dealing with many variables. Any suggestions?

If I've understood your question, I think you can just create the model formula with paste and use lapply to iterate through each new variable.

library(lme4)

vars = names(mtcars)[c(1,5,6,7)]

models = lapply(setNames(vars, vars), function(var) {
  form = paste("cyl ~ disp + hp + ", var, "+ (carb|gear)")
  lmer(form, data=mtcars)
})

A slight variant on @eipi10's solution:

library(lme4)
vars = names(mtcars)[c(1,5,6,7)]
otherVars <- c("disp","hp","(carb|gear)")
formList <- lapply(vars,function(x) {
       reformulate(c(otherVars,x),response="cyl")
})
modList <- lapply(formList,lmer,data=mtcars)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM