R:通过混合效应模型循环多个自变量

R: loop multiple independent variables through a mixed effect model

我希望通过混合效应模型循环一些自变量。有几个类似的问题,但对我来说没什么用。使用 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

因此,对于我的 'basic' 模型,我现在希望通过模型迭代地 运行 xnam2 中的每个变量作为固定效果,但无法使其与 [=21= 一起使用] 和粘贴方法:

f2 <- " +(carb|gear)"

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

所以 cyl ~ disp+hp + 循环变量 + (carb|gear) 就是我想要的。

希望这对我想要完成的事情很清楚。我对多个粘贴有点困惑,但似乎是处理许多变量的最佳方法。有什么建议吗?

如果我理解了您的问题,我认为您可以使用 paste 创建模型公式并使用 lapply 遍历每个新变量。

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 的解决方案略有不同:

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)