modelsummary and multiple comparisons from marginaleffects

183 views Asked by At
dat <- mtcars
dat$cyl <- as.factor(dat$cyl)
dat$am <- as.logical(dat$am)
dat$carb <- as.factor(dat$carb)
mod <- lm(mpg ~ hp + cyl + am+carb, data = dat)
mm_dat <- marginaleffects::comparisons(mod,variables =  list(carb="pairwise"),
                                        by="am",cross = T)

modelsummary(mm_dat,
             title = "Estimated Marginal Means",
             estimate = "{estimate} [{conf.low}, {conf.high}]",
             statistic = NULL,
             group = term ~ am)

Any idea how I can retrieve the results from marginaleffects into a summary with the estimates from mm_dat? I only get the length of the individual vectors

1

There are 1 answers

3
Vincent On BEST ANSWER

With version 1.2.0.9001 of modelsummary (only available from Github at the time of writing), you can do this:

library(modelsummary)
library(marginaleffects)

dat <- mtcars
dat$cyl <- as.factor(dat$cyl)
dat$am <- as.logical(dat$am)
dat$carb <- as.factor(dat$carb)
mod <- lm(mpg ~ hp + cyl + am+carb, data = dat)

cmp <- comparisons(
    mod,
    variables = list(carb = "sequential"),
    by = "am",
    cross = TRUE)

modelsummary(
    cmp,
    output = "markdown",
    shape = am + contrast_carb ~ model,
    estimate = "{estimate} [{conf.low}, {conf.high}]",
    statistic = NULL
)
am contrast_carb Model 1
TRUE mean(2) - mean(1) -0.517 [-3.513, 2.480]
TRUE mean(3) - mean(2) -0.029 [-4.183, 4.126]
TRUE mean(4) - mean(3) -1.718 [-6.405, 2.969]
TRUE mean(6) - mean(4) 0.204 [-6.683, 7.092]
TRUE mean(8) - mean(6) 1.814 [-7.380, 11.007]
FALSE mean(2) - mean(1) -0.517 [-3.513, 2.480]
FALSE mean(3) - mean(2) -0.029 [-4.183, 4.126]
FALSE mean(4) - mean(3) -1.718 [-6.405, 2.969]
FALSE mean(6) - mean(4) 0.204 [-6.683, 7.092]
FALSE mean(8) - mean(6) 1.814 [-7.380, 11.007]
Num.Obs. 32
R2 0.840
R2 Adj. 0.774
AIC 168.2
BIC 184.3
Log.Lik. -73.098
F 12.793
RMSE 2.38