[英]Extracting coefficients from multiple lmer models using lapply
I've been at this for a while but am unable to do this efficiently.我在这方面已经有一段时间了,但我无法有效地做到这一点。 I want to run many lmer models across multiple variables and extract coefficients from each model to put into a dataframe.我想跨多个变量运行多个 lmer 模型,并从每个模型中提取系数以放入数据帧。
So far I have the following到目前为止,我有以下内容
ivlist<-c("hp", "drat", "wt", "qsec", "vs", "am", "gear", "carb")
mtcars<-mtcars
mtcars$id<- sample(c(1:16), 32, replace=TRUE, prob = c(1/16, 1/16, 1/16, 1/16, 1/16, 1/16, 1/16, 1/16, 1/16, 1/16, 1/16, 1/16, 1/16, 1/16, 1/16, 1/16))
mod <- lapply(ivlist, function(x) {
lmer(substitute(mpg ~ cyl + disp + i*disp + (1|id), list(i = as.name(x))), data = mtcars, na.action=na.exclude)
})
res <- lapply(seq_along(mod[c(1:8)]), function(j) {
model = names(mod[[j]])
Vcov <- vcov(mod[[j]], useScale = FALSE)
betas <- fixef(mod[[j]])
se <- sqrt(diag(Vcov))
zval <- betas / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)})
do.call(cbind(names,betas, se, zval, pval), res)
I am now stuck.我现在卡住了。 It's telling me there is no se object.它告诉我没有 se 对象。 Can you guys help.你们能帮忙吗。 Even better if you can suggest how i can do this for only the interaction effect.如果你能建议我如何只为交互效果做到这一点,那就更好了。
Thank you in advance先感谢您
In R
, we get the last output as return
.在R
,我们得到最后一个输出作为return
。 Here, we may need to return all the objects in a list
or as a named vector在这里,我们可能需要以list
或命名向量的形式返回所有对象
res <- lapply(seq_along(mod[c(1:8)]), function(j) {
model <- names(mod[[j]])
Vcov <- vcov(mod[[j]], useScale = FALSE)
betas <- fixef(mod[[j]])
se <- sqrt(diag(Vcov))
zval <- betas / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
list(betas = betas, se = se, zval = zval, pval = pval)
})
do.call(rbind, lapply(res, as.data.frame))
# betas se zval pval
#(Intercept) 39.5138536412 2.988611e+00 13.2214778 6.595523e-40
#cyl 0.3492185844 9.057326e-01 0.3855648 6.998190e-01
#disp -0.0805987883 2.376294e-02 -3.3917859 6.943868e-04
#hp -0.1074943073 3.537576e-02 -3.0386435 2.376459e-03
#disp:hp 0.0003166872 1.121111e-04 2.8247615 4.731583e-03
#(Intercept)1 10.6595603973 1.187663e+01 0.8975240 3.694394e-01
#cyl1 -0.8828858263 7.606152e-01 -1.1607522 2.457427e-01
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.