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:

## Usage

marginalmeans(
model,
variables = NULL,
variables_grid = NULL,
vcov = TRUE,
conf_level = 0.95,
type = NULL,
transform_post = NULL,
interaction = NULL,
hypothesis = NULL,
wts = "equal",
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"

• Mixed-Models degrees of freedom: "satterthwaite", "kenward-roger"

• 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. When type is NULL, the default value is used. This default is the first model-related row in the marginaleffects:::type_dictionary dataframe.

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.

• "sequential": difference between an estimate and the estimate in the next row.

• "revpairwise", "revreference", "revsequential": inverse of the corresponding hypotheses, as described above.

• 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. The column names of the matrix are used as labels in the output.

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

wts

character value. Weights to use in the averaging.

• "equal": each combination of variables in variables_grid gets an equal weight.

• "cells": each combination of values for the variables in the variables_grid gets a weight proportional to its frequency in the original data.

• "proportional": each combination of values for the variables in the variables_grid -- except for those in the variables argument -- gets a weight proportional to its frequency in the original data.

by

Collapse marginal means into categories. Data frame with a by column of group labels, and merging columns shared by newdata or the data frame produced by calling the same function without the by argument.

...

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.

 Package Class Argument Documentation brms brmsfit ndraws brms::posterior_predict re_formula lme4 merMod include_random insight::get_predicted re.form lme4::predict.merMod allow.new.levels lme4::predict.merMod glmmTMB glmmTMB re.form glmmTMB::predict.glmmTMB allow.new.levels glmmTMB::predict.glmmTMB zitype glmmTMB::predict.glmmTMB mgcv bam exclude mgcv::predict.bam robustlmm rlmerMod re.form robustlmm::predict.rlmerMod allow.new.levels robustlmm::predict.rlmerMod

## Examples

library(marginaleffects)

# simple marginal means for each level of cyl
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")
#>   term value marginalmean std.error conf.low conf.high      p.value statistic
#> 1  cyl     4     23.11334  1.658224 19.86328  26.36340 3.690579e-44  13.93861
#> 2  cyl     6     20.38477  1.337106 17.76409  23.00545 1.765453e-52  15.24544
#> 3  cyl     8     16.21082  1.072551 14.10866  18.31299 1.304150e-51  15.11427

# collapse levels of cyl by averaging
by <- data.frame(
cyl = c(4, 6, 8),
by = c("4 & 6", "4 & 6", "8"))
marginalmeans(mod,
variables = "cyl",
by = by)
#>      by marginalmean std.error conf.low conf.high      p.value statistic
#> 1 4 & 6     21.74905  1.132084 19.53021  23.96790 2.964293e-82  19.21152
#> 2     8     16.21082  1.072551 14.10866  18.31299 1.304150e-51  15.11427

# pairwise differences between collapsed levels
marginalmeans(mod,
variables = "cyl",
by = by,
hypothesis = "pairwise")
#>        term marginalmean std.error conf.low conf.high      p.value statistic
#> 1 4 & 6 - 8     5.538228  1.513052   2.5727  8.503755 0.0002519178  3.660302

# interaction
marginalmeans(mod,
variables = c("cyl", "carb"),
interaction = TRUE)
#>    cyl carb marginalmean std.error  conf.low conf.high       p.value statistic
#> 1    6    4     19.14907  1.338478 16.525705  21.77244  1.990073e-46 14.306600
#> 2    6    1     23.08862  1.765271 19.628756  26.54849  4.320526e-39 13.079362
#> 3    6    2     22.85979  1.867465 19.199624  26.51995  1.875206e-34 12.241080
#> 4    6    3     22.61071  2.365152 17.975102  27.24633  1.178225e-21  9.559942
#> 5    6    6     17.56323  3.003716 11.676053  23.45040  5.000145e-09  5.847167
#> 6    6    8     17.03717  3.481207 10.214129  23.86021  9.878645e-07  4.894041
#> 7    4    4     21.87765  1.901048 18.151659  25.60363  1.199563e-30 11.508200
#> 8    4    1     25.81720  1.263909 23.339980  28.29441  9.729029e-93 20.426468
#> 9    4    2     25.58836  1.166714 23.301643  27.87508 1.286605e-106 21.931995
#> 10   4    3     25.33929  2.365152 20.703673  29.97490  8.787848e-27 10.713598
#> 11   4    6     20.29180  3.766424 12.909744  27.67385  7.142425e-08  5.387551
#> 12   4    8     19.76574  3.814283 12.289884  27.24160  2.194796e-07  5.182034
#> 13   8    4     14.97513  1.195291 12.632406  17.31786  5.217536e-36 12.528445
#> 14   8    1     18.91468  1.942030 15.108373  22.72099  2.042705e-22  9.739643
#> 15   8    2     18.68585  1.570513 15.607698  21.76399  1.213213e-32 11.897929
#> 16   8    3     18.43677  1.830964 14.848149  22.02540  7.540931e-24 10.069436
#> 17   8    6     13.38929  3.356162  6.811330  19.96724  6.622284e-05  3.989464
#> 18   8    8     12.86323  3.003716  6.976053  18.75040  1.848561e-05  4.282439

# collapsed interaction
by <- expand.grid(
cyl = unique(mtcars$cyl), carb = unique(mtcars$carb))
by$by <- ifelse( by$cyl == 4,
paste("Control:", by$carb), paste("Treatment:", by$carb))

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

# Compute and summarize marginal means
mm <- marginalmeans(mod)
summary(mm)
#>   Term Value  Mean Std. Error z value   Pr(>|z|) 2.5 % 97.5 %
#> 1   am FALSE 17.87      1.244  14.366 < 2.22e-16 15.43  20.31
#> 2   am  TRUE 23.11      0.974  23.724 < 2.22e-16 21.20  25.02
#> 3 carb     1 21.99      1.345  16.350 < 2.22e-16 19.35  24.63
#> 4 carb     2 21.48      1.025  20.955 < 2.22e-16 19.47  23.49
#> 5 carb     3 20.55      1.780  11.549 < 2.22e-16 17.06  24.04
#> 6 carb     4 18.82      1.042  18.065 < 2.22e-16 16.77  20.86
#> 7 carb     6 18.47      3.019   6.118 9.4743e-10 12.55  24.39
#> 8 carb     8 21.62      4.055   5.332 9.6936e-08 13.68  29.57
#>
#> Model type:  lm
#> Prediction type:  response
#> Results averaged over levels of: am, carb

# 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.5142619  1.477885 -3.410863   2.38234 0.7278616 -0.3479715

marginalmeans(mod, variables = "carb", hypothesis = lc)
#>     term marginalmean std.error  conf.low conf.high   p.value  statistic
#> 1 custom   -0.5142619  1.477885 -3.410863   2.38234 0.7278616 -0.3479715

# Multiple custom contrasts
lc <- matrix(c(
-2, 1, 1, 0, -1, 1,
-1, 1, 0, 0, 0, 0
),
ncol = 2,
dimnames = list(NULL, c("A", "B")))
marginalmeans(mod, variables = "carb", hypothesis = lc)
#>   term marginalmean std.error   conf.low conf.high   p.value  statistic
#> 1    A    1.1989451  6.149643 -10.854133  13.25202 0.8454229  0.1949618
#> 2    B   -0.5142619  1.477885  -3.410863   2.38234 0.7278616 -0.3479715