简体   繁体   中英

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.

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. 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 . Here, we may need to return all the objects in a list or as a named vector

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
# ...

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