Marginal means are adjusted predictions, averaged across a grid of categorical predictors, holding other numeric predictors at their means. To learn more, read the marginal means vignette, visit the package website, or scroll down this page for a full list of vignettes:

marginalmeans(
  model,
  variables = NULL,
  variables_grid = NULL,
  vcov = TRUE,
  conf_level = 0.95,
  type = "response",
  transform_post = NULL,
  interaction = NULL,
  hypothesis = NULL,
  by = NULL,
  ...
)

Arguments

model

Model object

variables

character vector Categorical predictors over which to compute marginal means. NULL calculates marginal means for all logical, character, or factor variables in the dataset used to fit model. Set interaction=TRUE to compute marginal means at combinations of the predictors specified in the variables argument.

variables_grid

character vector Categorical predictors used to construct the prediction grid over which adjusted predictions are averaged (character vector). NULL creates a grid with all combinations of all categorical predictors. This grid can be very large when there are many variables and many response levels, so it is advisable to select a limited number of variables in the variables and variables_grid arguments.

vcov

Type of uncertainty estimates to report (e.g., for robust standard errors). Acceptable values:

  • FALSE: Do not compute standard errors. This can speed up computation considerably.

  • TRUE: Unit-level standard errors using the default vcov(model) variance-covariance matrix.

  • String which indicates the kind of uncertainty estimates to return.

    • Heteroskedasticity-consistent: "HC", "HC0", "HC1", "HC2", "HC3", "HC4", "HC4m", "HC5". See ?sandwich::vcovHC

    • Heteroskedasticity and autocorrelation consistent: "HAC"

    • Other: "NeweyWest", "KernHAC", "OPG". See the sandwich package documentation.

  • One-sided formula which indicates the name of cluster variables (e.g., ~unit_id). This formula is passed to the cluster argument of the sandwich::vcovCL function.

  • Square covariance matrix

  • Function which returns a covariance matrix (e.g., stats::vcov(model))

conf_level

numeric value between 0 and 1. Confidence level to use to build a confidence interval.

type

string indicates the type (scale) of the predictions used to compute marginal effects or contrasts. This can differ based on the model type, but will typically be a string such as: "response", "link", "probs", or "zero". When an unsupported string is entered, the model-specific list of acceptable values is returned in an error message.

transform_post

(experimental) A function applied to unit-level adjusted predictions and confidence intervals just before the function returns results. For bayesian models, this function is applied to individual draws from the posterior distribution, before computing summaries.

interaction

TRUE, FALSE, or NULL

  • FALSE: Marginal means are computed for each predictor individually.

  • TRUE: Marginal means are computed for each combination of predictors specified in the variables argument.

  • NULL (default): Behaves like TRUE when the variables argument is specified and the model formula includes interactions. Behaves like FALSE otherwise.

hypothesis

specify a hypothesis test or custom contrast using a vector, matrix, string, or string formula.

  • String:

    • "pairwise": pairwise differences between estimates in each row.

    • "reference": differences between the estimates in each row and the estimate in the first row.

  • String formula to specify linear or non-linear hypothesis tests. If the term column uniquely identifies rows, terms can be used in the formula. Otherwise, use b1, b2, etc. to identify the position of each parameter. Examples:

    • hp = drat

    • hp + drat = 12

    • b1 + b2 + b3 = 0

  • Numeric vector: Weights to compute a linear combination of (custom contrast between) estimates. Length equal to the number of rows generated by the same function call, but without the hypothesis argument.

  • Numeric matrix: Each column is a vector of weights, as describe above, used to compute a distinct linear combination of (contrast between) estimates.

  • See the Examples section below and the vignette: https://vincentarelbundock.github.io/marginaleffects/articles/hypothesis.html

by

character vector of categorical variables included in the variables_grid. Marginal means are computed within each subgroup corresponding to combinations of values in the by variables. Note that the by argument works differently for other functions in the package (predictions(), marginaleffects(), comparisons()), where by is used for post-processing in the tidy() or summary() functions.

...

Additional arguments are passed to the predict() method supplied by the modeling package.These arguments are particularly useful for mixed-effects or bayesian models (see the online vignettes on the marginaleffects website). Available arguments can vary from model to model, depending on the range of supported arguments by each modeling package. See the "Model-Specific Arguments" section of the ?marginaleffects documentation for a non-exhaustive list of available arguments.

Value

Data frame of marginal means with one row per variable-value combination.

Details

This function begins by calling the predictions function to obtain a grid of predictors, and adjusted predictions for each cell. The grid includes all combinations of the categorical variables listed in the variables and variables_grid arguments, or all combinations of the categorical variables used to fit the model if variables_grid is NULL. In the prediction grid, numeric variables are held at their means.

After constructing the grid and filling the grid with adjusted predictions, marginalmeans computes marginal means for the variables listed in the variables argument, by average across all categories in the grid.

marginalmeans can only compute standard errors for linear models, or for predictions on the link scale, that is, with the type argument set to "link".

The marginaleffects website compares the output of this function to the popular emmeans package, which provides similar but more advanced functionality: https://vincentarelbundock.github.io/marginaleffects/

Model-Specific Arguments

Some model types allow model-specific arguments to modify the nature of marginal effects, predictions, marginal means, and contrasts.

PackageClassArgumentDocumentation
brmsbrmsfitndrawsbrms::posterior_predict
re_formula
lme4merModinclude_randominsight::get_predicted
re.formlme4::predict.merMod
allow.new.levelslme4::predict.merMod
glmmTMBglmmTMBre.formglmmTMB::predict.glmmTMB
allow.new.levelsglmmTMB::predict.glmmTMB
zitypeglmmTMB::predict.glmmTMB
mgcvbamexcludemgcv::predict.bam
robustlmmrlmerModre.formrobustlmm::predict.rlmerMod
allow.new.levelsrobustlmm::predict.rlmerMod

Examples

library(marginaleffects)

# Convert numeric variables to categorical before fitting the model
dat <- mtcars
dat$cyl <- as.factor(dat$cyl)
dat$am <- as.logical(dat$am)
mod <- lm(mpg ~ hp + cyl + am, data = dat)

# Compute and summarize marginal means
mm <- marginalmeans(mod)
summary(mm)
#> Estimated marginal means 
#>   Term Value  Mean Std. Error z value   Pr(>|z|) 2.5 % 97.5 %
#> 1   am FALSE 18.32     0.7854   23.33 < 2.22e-16 16.78  19.86
#> 2   am  TRUE 22.48     0.8343   26.94 < 2.22e-16 20.84  24.11
#> 3  cyl     4 22.88     1.3566   16.87 < 2.22e-16 20.23  25.54
#> 4  cyl     6 18.96     1.0729   17.67 < 2.22e-16 16.86  21.06
#> 5  cyl     8 19.35     1.3771   14.05 < 2.22e-16 16.65  22.05
#> 
#> Model type:  lm 
#> Prediction type:  response 
#> Results averaged over levels of: cyl, am 

# Marginal means by subgroup
dat <- mtcars
dat$carb <- factor(dat$carb)
dat$cyl <- factor(dat$cyl)
dat$am <- as.logical(dat$am)
mod <- lm(mpg ~ carb + cyl + am, dat)
marginalmeans(mod, variables = "cyl", by = "am")
#>      am term value marginalmean std.error conf.low conf.high      p.value
#> 1  TRUE  cyl     4     25.25011  1.658224 22.00005  28.50017 2.333708e-52
#> 2 FALSE  cyl     4     20.97657  1.337106 18.35589  23.59724 1.826223e-55
#> 3  TRUE  cyl     6     22.52154  1.072551 20.41938  24.62370 6.825898e-98
#> 4 FALSE  cyl     6     18.24799  1.658224 14.99793  21.49805 3.633622e-28
#> 5  TRUE  cyl     8     18.34760  1.337106 15.72692  20.96828 7.510116e-43
#> 6 FALSE  cyl     8     14.07405  1.072551 11.97189  16.17621 2.462394e-39
#>   statistic
#> 1  15.22720
#> 2  15.68803
#> 3  20.99810
#> 4  11.00454
#> 5  13.72187
#> 6  13.12203

# Contrast between marginal means (carb2 - carb1), or "is the 1st marginal means equal to the 2nd?"
# see the vignette on "Hypothesis Tests and Custom Contrasts" on the `marginaleffects` website.
lc <- c(-1, 1, 0, 0, 0, 0)
marginalmeans(mod, variables = "carb", hypothesis = "b2 = b1")
#>    term marginalmean std.error  conf.low conf.high   p.value  statistic
#> 1 b2=b1    -0.228836  1.540681 -3.248516  2.790844 0.8819252 -0.1485291

marginalmeans(mod, variables = "carb", hypothesis = lc)
#>     term marginalmean std.error  conf.low conf.high   p.value  statistic
#> 1 custom    -0.228836  1.540681 -3.248516  2.790844 0.8819252 -0.1485291

# Multiple custom contrasts
lc <- matrix(c(
    -2, 1, 1, 0, -1, 1,
    -1, 1, 0, 0, 0, 0
    ), ncol = 2)
marginalmeans(mod, variables = "carb", hypothesis = lc)
#>     term marginalmean std.error   conf.low conf.high   p.value  statistic
#> 1 custom    -1.232804  6.027062 -13.045628 10.580020 0.8379278 -0.2045448
#> 2 custom    -0.228836  1.540681  -3.248516  2.790844 0.8819252 -0.1485291