rmodelsummaryr-marginaleffects

Is ther a way in R and modelsummary to stack a comparisons table produced by marginal effects


I ran several linear regressions and obtained comparisons from the avg_comparisons function of the marginaleffects package and then form it with the shape = term : contrast ~ model option parameters of the modelsummary package to concatenate the term and contrast. This results in the desired first part of the table. Now I wanted to make two panels and stacked them. With standard regressions this works very fine with the shape = "rbind" function, but not when I need to concatenate term and contrast before. Is there a way in the syntax of the shape option that allows to combine this two different behaviors? Or is there another way of achieving the stacking of the panels?

I ran the following code to produce the comparisons

vars <- c("var1", "var2", "var3")

panel1 <- vars %>%
    paste(., "~ Treatment") %>%
    map(as.formula) %>%
    map(lm, data = df) %>% 
    map(avg_comparisons, variables = "Treatment", vcov = "hc1") 
modelsummary(panel1, shape = term : contrast ~ model)

this produced the desired outcome for one panel. Then I tried to add another panel

vars <- c("var4", "var5")

panel2 <- vars2 %>%
    paste(., "~ Treatment") %>%
    map(as.formula) %>%
    map(lm, data = df) %>% 
    map(avg_comparisons, variables = "Treatment", vcov = "hc1") 

panels(list(panel1, panel2))

modelsummary(panels, shape = term : contrast ~ model)

This produced an error, as modelsummary does not accept the inputs as list, when shape is not "rbind".


Solution

  • Unfortunately, I can't think of a completely automatic way to do this right now. What you could do is proceed in steps: Create an intermediate representation in modelsummary_list format, combine the labels, and feed the result back to modelsummary. Example:

    library(modelsummary)
    library(marginaleffects)
    
    # fit
    mod <- list(
      lm(mpg ~ am + factor(cyl), data = mtcars),
      lm(mpg ~ hp + am + factor(cyl), data = mtcars)
    )
    
    mod <- lapply(mod, avg_comparisons)
    
    # intermediate representation
    tab <- modelsummary(mod, output = "modelsummary_list")
    
    # combine labels
    tab[[1]]$tidy$term <- paste(tab[[1]]$tidy$term, tab[[1]]$tidy$contrast)
    tab[[2]]$tidy$term <- paste(tab[[2]]$tidy$term, tab[[2]]$tidy$contrast)
    
    # back to modelsummary
    modelsummary(tab, shape = "rbind", gof_map = "nobs")
    

    enter image description here