Search code examples
rmodelsummary

Using modelsummary for list-columns of models


I am often fitting models in this manner:


mtcars %>% 
  nest(-cyl) %>% 
  mutate(model=map(data, function(x) lm(hp~mpg, data=x)), 
         model2=map(data, function(x) lm(hp~mpg+wt, data=x)))->models
library(tidyverse)
models

To my mind, because models$model and models$model2 are list (specifically list-columns), modelsummary should work. But it doesn't. it requires some modification.

this works:

models %>% 
  pivot_longer(c(model:model2)) %>% 
  select(value) %>% 
  as.list() %>% 
  map(., modelsummary,output="kableExtra", stars=T)

But, from here I don't know how to post-process the table (e.g. add header rows).

models %>% 
  pivot_longer(c(model:model2)) %>% 
  select(value) %>% 
  as.list() %>% 
  map(., modelsummary,output="kableExtra", stars=T) %>% 
  add_header_above(header=c(" "=1, "4"=2:3, "6"=4:5))

What is the quickest way to use modelsummary to work with list-columns Thank you!


Solution

  • This is documented in a vignette: https://modelsummary.com/vignettes/modelsummary.html#subgroup-estimation-with-nest_by

    The other answer is adequate, but here I give an example using the tinytable output format, which is now default in modelsummary 2.0.0.

    Note that we use group_tt() instead of add_header_above(). Also note that the group_tt() function uses a syntax very similar to what the original poster intuitively -- but erroneously -- used in add_header_above().

    library(tidyverse)
    library(modelsummary)
    library(tinytable)
    
    mtcars %>% 
      nest(data = -cyl) |>
      mutate(model=map(data, function(x) lm(hp~mpg, data=x)), 
             model2=map(data, function(x) lm(hp~mpg+wt, data=x)))->models
    
    models |>
      pivot_longer(c(model:model2)) |>
      pull(value) |>
      modelsummary(stars = TRUE) |>
      group_tt(j = list("6" = 2:3, "4" = 4:5, "8" = 6:7))
    

    enter image description here