提问人:12666727b9 提问时间:8/29/2023 更新时间:8/29/2023 访问量:31
嵌套后无法访问因变量以拟合 LMER 模型
cannot acces to dependent variable after nesting for fitting lmer models
问:
我一直在尝试拟合这样的模型
mtcars %>%
mutate(vs = factor(vs), gear = factor(gear), carb = factor(carb), am = factor(am),
cyl = factor(cyl)) %>% nest_by(vs) %>%
do(fit = lmer(.,formula= mpg ~ cyl + disp + hp + (1 | am) + (1 | vs)))
但不幸的是,我看到我无法访问 cyl 变量,正如我收到的错误中所报告的那样。
Error in eval(predvars, data, env) : object 'cyl' not found
谁能帮我找出问题所在?
谢谢
答:
3赞
William Wong
8/29/2023
#1
您可能想拥抱 tidyvrese 并忘记 .您可能还希望删除模型中的变量,因为您已选择对每个组执行单独的测试。do()
vs
library(tidyverse)
library(lme4)
library(broom.mixed)
mtcars %>%
mutate(vs = factor(vs), gear = factor(gear), carb = factor(carb), am = factor(am),
cyl = factor(cyl)) %>%
# replacing nest_by with group_by
group_by(vs) %>%
# either using nest_by or group_by, you may want to make sure that the "grouping variable" (vs) is not in the nested table
# using group_modify is a cleaner way to do the job (with tidy)
group_modify(~ broom::tidy(lmer(formula= mpg ~ cyl + disp + hp + (1 | am), data = .x)))
仅供参考,如果您坚持使用大部分代码。您应该让 do() 知道输入是输入数据框的列。data
.
test <- mtcars %>%
mutate(vs = factor(vs), gear = factor(gear), carb = factor(carb), am = factor(am),
cyl = factor(cyl)) %>% nest_by(vs) %>%
do(fit = lmer(.$data,formula= mpg ~ cyl + disp + hp + (1 | am) ))
test$fit
评论
lmer
lme4
mutate(across(c(vs, gear, carb, am, cyl), \(x) factor(x)))
mutate(across(c(vs, gear, carb, am, cyl), factor))