1

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?

SlyGrogger
  • 317
  • 5
  • 16

2 Answers2

2

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)
})
eipi10
  • 91,525
  • 24
  • 209
  • 285
  • Cheers. Is it possible to preserve the paste(fla) part of my code through this solution? (eg. replacing "cyl ~ disp + hp + " with paste(fla) or something). Reason being that I want to keep away from needing to call variables manually (could be up to 50 in real world data). – SlyGrogger May 31 '17 at 23:53
  • Yes, you can use `paste` or `reformulate` to create your model formula and select the variables programmatically by, for example, position, string matching, etc. – eipi10 Jun 01 '17 at 00:25
1

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)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • When running this, I receive the error message: Error: 'data' not found, and some variables missing from formula environment – SlyGrogger May 31 '17 at 23:57