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?