can't use emmeans inside map

£可爱£侵袭症+ 提交于 2021-01-24 08:12:29

问题


This works:

testmodel=glm(breaks~wool,data=warpbreaks)
emmeans::emmeans(testmodel,"wool")

This works:

warpbreaks %>%
  group_by(tension) %>%
  do(models=glm(breaks~wool,data=.)) %>% 
  ungroup() %>%
  mutate(means=map(models,~emmeans::emmeans(.x,"wool")))

This doesn't:

warpbreaks %>%
  group_by(tension) %>% nest() %>%
  mutate(models=map(data,~glm(breaks~wool,data=.x))) %>%
  mutate(means=map(models,~emmeans::emmeans(.x,"wool")))

Error in is.data.frame(data) : object '.x' not found
Error in mutate_impl(.data, dots) : 
  Evaluation error: Perhaps a 'data' or 'params' argument is needed.

Any idea what's causing this?


回答1:


I figured it out. The issue is the way emmeans tries to recover data from lm/glm objects: it tries to run the call stored in the object, which fails if emmeans() is called in a different environment than the original glm() call:

emmeans:::recover_data.lm

Here's an easy example:

wb=warpbreaks
model=glm(breaks~wool,data=wb)
emmeans(model,"wool")
rm(wb)
emmeans(model,"wool")

Here's the way to make emmeans() work with map():

warpbreaks %>%
  group_by(tension) %>% nest() %>%
  mutate(models=map(data,~glm(breaks~wool,data=.x))) %>%
  mutate(means=map(models,~emmeans::emmeans(.x,"wool",data=.x$data)))

It seems strange that recover_data() doesn't just automatically use the data attribute of the lm/glm objects and instead assumes that the call will function in the current environment...




回答2:


We can do it in a two-step process

df1 <- warpbreaks %>%
            group_by(tension) %>%
            nest() %>%
            mutate(models = map(data,~glm(breaks~wool,data=.x)))                          

warpbreaks %>% 
      split(.$tension) %>% 
       map( ~glm(breaks ~ wool, data = .x) %>%
                emmeans(., "wool")) %>%
       mutate(df1, Means = .) 

# A tibble: 3 x 4
#   tension data              models    Means        
#  <fctr>  <list>            <list>    <list>       
#1 L       <tibble [18 x 2]> <S3: glm> <S4: emmGrid>
#2 M       <tibble [18 x 2]> <S3: glm> <S4: emmGrid>
#3 H       <tibble [18 x 2]> <S3: glm> <S4: emmGrid>


来源:https://stackoverflow.com/questions/48576160/cant-use-emmeans-inside-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!