gpt4 book ai didi

r - lapply 与回归模型的多个列表和函数

转载 作者:行者123 更新时间:2023-12-05 03:46:26 24 4
gpt4 key购买 nike

我想使用 lapply 同时运行四个多级模型(使用 lmer)。

将 lm() 与一个因变量和一组自变量一起使用的简单示例是:

data(mtcars)
varlist <- names(mtcars)[3:6]

models <- lapply(varlist, function(x) {
lm(substitute(mpg ~ i, list(i = as.name(x))), data = mtcars)
})

我如何扩展它以运行四个 lmer() 模型,每个模型都有不同的因变量和不同的自变量列表?对于所有四个模型,这两个级别将保持不变。四个(伪造的)示例模型是:

data(mtcars)
library(lme4)

model1 <- lmer(mpg ~ cyl + disp + hp + (1 | am) + (1 | vs), data = mtcars)

model2 <- lmer(cyl ~ mpg + disp + qsec + (1 | am) + (1 | vs), data = mtcars)

model3 <- lmer(disp ~ mpg + cyl + carb + (1 | am) + (1 | vs), data = mtcars)

model4 <- lmer(qsec ~ mpg + cyl + drat + (1 | am) + (1 | vs), data = mtcars)

有什么想法吗?

最佳答案

我们可以有一个依赖(或向量)和自变量的列表,并将其传递到Map中以创建公式 并应用 lmerlist 的单位元素在这里是自变量的 vector 和因变量的单个元素。

library(lme4)
indep_var_list <- list(c("cyl", "disp", "hp"),
c("mpg", "disp", "qsec"),
c("mpg", "cyl", "carb"),
c("mpg", "cyl", "drat"))

dep_vars <- c("mpg", "cyl", "disp", "qsec")

out <- Map(function(x, y) {

fmla <- as.formula(paste(y, "~ ", paste(x, collapse= " + ") ,
" + (1 | am) + (1 | vs)"))
model <- lmer(fmla, data = mtcars)
model
}, indep_var_list, dep_vars)


-输出

[1]]
Linear mixed model fit by REML ['lmerMod']
Formula: mpg ~ cyl + disp + hp + (1 | am) + (1 | vs)
Data: mtcars
REML criterion at convergence: 169.5913
Random effects:
Groups Name Std.Dev.
am (Intercept) 2.209
vs (Intercept) 0.000
Residual 2.831
Number of obs: 32, groups: am, 2; vs, 2
Fixed Effects:
(Intercept) cyl disp hp
32.55270 -0.90447 -0.00972 -0.02971
convergence code 0; 0 optimizer warnings; 1 lme4 warnings

[[2]]
Linear mixed model fit by REML ['lmerMod']
Formula: cyl ~ mpg + disp + qsec + (1 | am) + (1 | vs)
Data: mtcars
REML criterion at convergence: 78.0586
Random effects:
Groups Name Std.Dev.
am (Intercept) 0.5773
vs (Intercept) 0.4491
Residual 0.5743
Number of obs: 32, groups: am, 2; vs, 2
Fixed Effects:
(Intercept) mpg disp qsec
10.592032 -0.045832 0.006052 -0.279176

[[3]]
Linear mixed model fit by REML ['lmerMod']
Formula: disp ~ mpg + cyl + carb + (1 | am) + (1 | vs)
Data: mtcars
REML criterion at convergence: 316.1521
Random effects:
Groups Name Std.Dev.
am (Intercept) 0.00
vs (Intercept) 0.00
Residual 49.83
Number of obs: 32, groups: am, 2; vs, 2
Fixed Effects:
(Intercept) mpg cyl carb
112.57 -7.15 47.90 -12.30
convergence code 0; 0 optimizer warnings; 1 lme4 warnings

[[4]]
Linear mixed model fit by REML ['lmerMod']
Formula: qsec ~ mpg + cyl + drat + (1 | am) + (1 | vs)
Data: mtcars
REML criterion at convergence: 92.9165
Random effects:
Groups Name Std.Dev.
am (Intercept) 1.4979
vs (Intercept) 0.6131
Residual 0.9008
Number of obs: 32, groups: am, 2; vs, 2
Fixed Effects:
(Intercept) mpg cyl drat
24.5519 0.0288 -0.7956 -0.6974

关于r - lapply 与回归模型的多个列表和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65295644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com