不能在地图中使用emmeans

时间:2018-02-02 05:21:19

标签: r purrr emmeans

这有效:

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

这有效:

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

这不是:

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.

知道造成这种情况的原因是什么?

2 个答案:

答案 0 :(得分:2)

我明白了。问题是emmeans尝试从lm / glm对象恢复数据的方式:它尝试运行存储在对象中的调用,如果在与原始glm()调用不同的环境中调用emmeans(),则该调用将失败:

emmeans:::recover_data.lm

这是一个简单的例子:

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

这是使emmeans()与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)))

看起来很奇怪,recover_data()不仅会自动使用lm / glm对象的data属性,而是假设调用将在当前环境中运行...

答案 1 :(得分:0)

我们可以分两步完成

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>