Problems mutate-ing and select-ing over a list of tibbles

53 views Asked by At

I'm trying to reproduce a graph from Clause Willke's data visualization guide (https://clauswilke.com/dataviz/visualizing-uncertainty.html#fig:cocoa-data-vs-CI), and the code he wrote is choking for me.

I apologize in advance if this is long, but trying to explain what I think is going on. (Also, you can find the cacao data at https://github.com/clauswilke/dviz.supp/blob/master/data/cacao.rda.)

Full code chunk:

cacao %>% 
  filter(location == "Canada") -> cacao_single

fit <- lm(rating ~ 1, data = cacao_single)

CI_df <- data.frame(type = c(0.8, 0.95, 0.99)) %>%
  mutate(df = map(type, ~tidy(emmeans(fit, ~ 1, options = list(level = .x)
  )))) %>%
  unnest(c()) %>%
  select(type, estimate, std.error, conf.low, conf.high) %>%
  mutate(type = paste0(signif(100*type, 2), "% confidence interval"))
Error: Can't subset columns that don't exist.
x Column `estimate` doesn't exist.

The emmeans() function normally returns the beta estimate, SE, df, and upper and lower confidence bounds, as in:

> emmeans(fit, ~1)
 1       emmean     SE  df lower.CL upper.CL
 overall   3.32 0.0379 124     3.25      3.4

Confidence level used: 0.95 

When I run the piped statement above, I get a list of tibbles, but the list-element tibbles do not have CIs attached. This is in addition to the select() not finding estimate (as the error message appears to indicate). Thus,

  1. Why doesn't the list of tibbles have the CIs associated with each confidence level in the type column? Should it?
  2. How can I get select() to, well, select?
1

There are 1 answers

12
KM_83 On

Try removing c() in unnest() (it gives a warning but it works). It may be that unnest() syntax has changed.

CI_df <- data.frame(type = c(0.8, 0.95, 0.99)) %>%
  mutate(df = map(type, ~generics::tidy(emmeans(fit, ~ 1, options = list(level = .x)
  ))))  %>%
  #unnest(c()) %>%
  unnest() %>%
  select(type, estimate, std.error, conf.low, conf.high) %>%
  mutate(type = paste0(signif(100*type, 2), "% confidence interval"))