嵌套后无法访问因变量以拟合 LMER 模型

cannot acces to dependent variable after nesting for fitting lmer models

提问人:12666727b9 提问时间:8/29/2023 更新时间:8/29/2023 访问量:31

问:

我一直在尝试拟合这样的模型

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

谁能帮我找出问题所在?

谢谢

R 套嵌 LME4

评论

1赞 stefan_aus_hannover 8/29/2023
软件包在哪个库中?lmer
1赞 12666727b9 8/29/2023
在。这就是我正在使用的那个,但如果您建议使用 lmerTest,也许这会改变输出lme4
1赞 GuedesBF 8/29/2023
与问题无关。但是您可以考虑清理调用以进行突变,或者只是mutate(across(c(vs, gear, carb, am, cyl), \(x) factor(x)))mutate(across(c(vs, gear, carb, am, cyl), factor))

答:

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