knitr::opts_chunk$set( collapse = TRUE, fig.width = 6, fig.asp = .4, warning = FALSE, message = FALSE, comment = "#>" ) library(marginaleffects) library(patchwork) library(ggplot2) theme_set(theme_minimal())
In a previous vignette, we introduced the "marginal effect" as a partial derivative. Since derivatives are only properly defined for continuous variables, we cannot use them to interpret the effects of changes in categorical variables. For this, we turn to contrasts between Adjusted predictions. In the context of this package, a "Contrast" is defined as:
The difference between two adjusted predictions, calculated for meaningfully different regressor values (e.g., College graduates vs. Others).
Consider a simple model with a logical and a factor variable:
library(marginaleffects) tmp <- mtcars tmp$am <- as.logical(tmp$am) mod <- lm(mpg ~ am + factor(cyl), tmp)
marginaleffects function automatically computes contrasts for each level of the categorical variables, relative to the baseline category (
FALSE for logicals, and the reference level for factors), while holding all other values at their mode or mean:
mfx <- marginaleffects(mod) summary(mfx)
The summary printed above says that moving from the reference category
4 to the level
6 on the
cyl factor variable is associated with a change of
r sprintf("%.3f", tidy(mfx)$estimate) in the adjusted prediction. Similarly, the contrast from
TRUE on the
am variable is equal to
r sprintf("%.3f", tidy(mfx)$estimate).
We can obtain the same results using the
library(emmeans) emm <- emmeans(mod, specs = "cyl") contrast(emm, method = "revpairwise") emm <- emmeans(mod, specs = "am") contrast(emm, method = "revpairwise")
In models with multiplicative interactions, the contrasts of a categorical variable will depend on the values of the interacted variable:
mod_int <- lm(mpg ~ am * factor(cyl), tmp)
We can now use the
newdata argument of the
marginaleffects function to compute contrasts for different values of the other regressors. As in the marginal effects vignette, the
typical function can be handy. Since we only care about the logical
am contrast, we use the
variables to indicate the subset of results to report:
marginaleffects(mod_int, newdata = typical(cyl = tmp$cyl), variables = "am")
Once again, we obtain the same results with
emm <- emmeans(mod_int, specs = "am", by = "cyl") contrast(emm, method = "revpairwise")
As described above, the
marginaleffects package includes limited support to compute contrasts. Users who require more powerful features are encouraged to consider alternative packages such as emmeans, modelbased, or ggeffects. These packages offer useful features such as automatic back-transforms, p value correction for multiple comparisons, and more.
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.