Nicholas Root
Nicholas Root

Reputation: 555

can't use emmeans inside map

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?

Upvotes: 2

Views: 461

Answers (2)

Nicholas Root
Nicholas Root

Reputation: 555

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

Upvotes: 4

akrun
akrun

Reputation: 887711

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>

Upvotes: 0

Related Questions