Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot acces to dependent variable after nesting for fitting lmer models

I have been trying to fitting such model

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)))

But unfortunately I am seeing that I cannot access to the cyl variable, as reported in the error I am getting.

Error in eval(predvars, data, env) : object 'cyl' not found

Can anyone just help me figuring out which the problem is?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

You may want to embrace the tidyvrese and forget about the do(). You may also want to remove the vs variable in your model because you have chosen performing separate test for each group.

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)))

FYI, if you insist using most of your code. You should let the do() know the input is the data column of the input data frame ..

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading