Juan Pablo Ospina
Juan Pablo Ospina

Reputation: 35

map emmeans from a list of linear models in R

I have a list of over ~100 linear models and I want to take the estimated means and standard errors for each model.

Let's use mtcars as an example.

library(tidyverse); library(magrittr); library(emmeans)

mtcars %<>% 
  mutate(
    cyl = as.factor(cyl)
  )

df <- mtcars %>% select(cyl, hp, mpg)

I can easily get the estimated means and standard errors for each model with emmeans:

mod <- lm(hp ~ cyl, data = df)
emmeans(mod, "cyl")

But what if I have a list of models?

list_lm <- df %>% 
   select(-c(cyl)) %>%
   map(function(dv) lm(dv ~ df$cyl, data = .)) 

I cannot use:

emmeans(list_lm$hp, "cyl")
Error in ref_grid(object, ...) : Perhaps a 'data' or 'params' argument is needed

And ideally, I want something that would give me these statistics for all the models. Something like broom::tidy for the coefficients of the model, but for emmeans:

list_lm %>% 
   map(broom::tidy)

Upvotes: 3

Views: 936

Answers (1)

Joe
Joe

Reputation: 3806

Your intuitions were right. The solution requires saving intermediate results in list columns and then unpacking them, but given the structure of emmeans output, broom::tidy() is not necessary. Just convert emmeans output to a list column of data.frames and unnest().

library(dplyr)
library(purrr)
library(tidyr)
library(emmeans)

ds_mtcars <- 
  mtcars %>% 
  mutate(cyl = as.factor(cyl)) 

ds_nest <- 
  ds_mtcars %>% 
  group_by(am) %>% 
  nest() 

foo_model <- function(data){
  lm(hp ~ cyl, data = data)
}

ds_nest <- ds_nest %>% mutate(model = map(.x = data, .f = foo_model))

ds_temp <- 
  ds_nest %>% 
  mutate(
    emmeans = pmap(
      .l = list(
        object = model, 
        specs = "cyl"
      ),
      .f = emmeans
    )
  ) 

ds_temp %>% 
  mutate(emm2 = map(emmeans, data.frame)) %>% 
  unnest(emm2)

Also the purrr functions map() and pmap() can be a mind bender, but I did my best to walk myself and new users through these functions on my blog.

Upvotes: 5

Related Questions