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:
marginal_means(
model,
variables = NULL,
newdata = NULL,
vcov = TRUE,
conf_level = 0.95,
type = NULL,
transform = NULL,
cross = FALSE,
hypothesis = NULL,
equivalence = NULL,
p_adjust = NULL,
df = Inf,
wts = "equal",
by = NULL,
numderiv = "fdforward",
...
)
Data frame of marginal means with one row per variable-value combination.
Model object
Focal variables
Character vector of variable names: compute marginal means for each category of the listed variables.
NULL
: calculate marginal means for all logical, character, or factor variables in the dataset used to fit model
. Hint: Set cross=TRUE
to compute marginal means for combinations of focal variables.
Grid of predictor values over which we marginalize.
Warning: Please avoid modifying your dataset between fitting the model and calling a marginaleffects
function. This can sometimes lead to unexpected results.
NULL
create a grid with all combinations of all categorical predictors in the model. Warning: can be expensive.
Character vector: subset of categorical variables to use when building the balanced grid of predictors. Other variables are held to their mean or mode.
Data frame: A data frame which includes all the predictors in the original model. The full dataset is replicated once for every combination of the focal variables in the variables
argument, using the datagridcf()
function.
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)
)
numeric value between 0 and 1. Confidence level to use to build a confidence interval.
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
first entry in the error message is used by default.
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.
TRUE or FALSE
FALSE
(default): Marginal means are computed for each predictor individually.
TRUE
: Marginal means are computed for each combination of predictors specified in the variables
argument.
specify a hypothesis test or custom contrast using a numeric value, vector, or matrix, a string, or a string formula.
Numeric:
Single value: the null hypothesis used in the computation of Z and p (before applying transform
).
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.
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.
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. The b*
wildcard can be used to test hypotheses on all estimates. Examples:
hp = drat
hp + drat = 12
b1 + b2 + b3 = 0
b* / b1 = 1
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.
See the Examples section below and the vignette: https://marginaleffects.com/vignettes/hypothesis.html
Numeric vector of length 2: bounds used for the two-one-sided test (TOST) of equivalence, and for the non-inferiority and non-superiority tests. See Details section below.
Adjust p-values for multiple comparisons: "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", or "fdr". See stats::p.adjust
Degrees of freedom used to compute p values and confidence intervals. A single numeric value between 1 and Inf
. When df
is Inf
, the normal distribution is used. When df
is finite, the t
distribution is used. See insight::get_df for a convenient function to extract degrees of freedom. Ex: slopes(model, df = insight::get_df(model))
character value. Weights to use in the averaging.
"equal": each combination of variables in newdata
gets equal weight.
"cells": each combination of values for the variables in the newdata
gets a weight proportional to its frequency in the original data.
"proportional": each combination of values for the variables in newdata
-- except for those in the variables
argument -- gets a weight proportional to its frequency in the original data.
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.
string or list of strings indicating the method to use to for the numeric differentiation used in to compute delta method standard errors.
"fdforward": finite difference method with forward differences
"fdcenter": finite difference method with central differences (default)
"richardson": Richardson extrapolation method
Extra arguments can be specified by passing a list to the numDeriv
argument, with the name of the method first and named arguments following, ex: numderiv=list("fdcenter", eps = 1e-5)
. When an unknown argument is used, marginaleffects
prints the list of valid arguments for each method.
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.
Standard errors for all quantities estimated by marginaleffects
can be obtained via the delta method. This requires differentiating a function with respect to the coefficients in the model using a finite difference approach. In some models, the delta method standard errors can be sensitive to various aspects of the numeric differentiation strategy, including the step size. By default, the step size is set to 1e-8
, or to 1e-4
times the smallest absolute model coefficient, whichever is largest.
marginaleffects
can delegate numeric differentiation to the numDeriv
package, which allows more flexibility. To do this, users can pass arguments to the numDeriv::jacobian
function through a global option. For example:
options(marginaleffects_numDeriv = list(method = "simple", method.args = list(eps = 1e-6)))
options(marginaleffects_numDeriv = list(method = "Richardson", method.args = list(eps = 1e-5)))
options(marginaleffects_numDeriv = NULL)
See the "Standard Errors and Confidence Intervals" vignette on the marginaleffects
website for more details on the computation of standard errors:
https://marginaleffects.com/vignettes/uncertainty.html
Note that the inferences()
function can be used to compute uncertainty estimates using a bootstrap or simulation-based inference. See the vignette:
https://marginaleffects.com/vignettes/bootstrap.html
Some model types allow model-specific arguments to modify the nature of
marginal effects, predictions, marginal means, and contrasts. Please report
other package-specific predict()
arguments on Github so we can add them to
the table below.
https://github.com/vincentarelbundock/marginaleffects/issues
Package | Class | Argument | Documentation |
brms | brmsfit | ndraws | brms::posterior_predict |
re_formula | brms::posterior_predict | ||
lme4 | merMod | 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 | ||
MCMCglmm | MCMCglmm | ndraws |
By default, credible intervals in bayesian models are built as equal-tailed intervals. This can be changed to a highest density interval by setting a global option:
options("marginaleffects_posterior_interval" = "eti")
options("marginaleffects_posterior_interval" = "hdi")
By default, the center of the posterior distribution in bayesian models is identified by the median. Users can use a different summary function by setting a global option:
options("marginaleffects_posterior_center" = "mean")
options("marginaleffects_posterior_center" = "median")
When estimates are averaged using the by
argument, the tidy()
function, or
the summary()
function, the posterior distribution is marginalized twice over.
First, we take the average across units but within each iteration of the
MCMC chain, according to what the user requested in by
argument or
tidy()/summary()
functions. Then, we identify the center of the resulting
posterior using the function supplied to the
"marginaleffects_posterior_center"
option (the median by default).
\(\theta\) is an estimate, \(\sigma_\theta\) its estimated standard error, and \([a, b]\) are the bounds of the interval supplied to the equivalence
argument.
Non-inferiority:
\(H_0\): \(\theta \leq a\)
\(H_1\): \(\theta > a\)
\(t=(\theta - a)/\sigma_\theta\)
p: Upper-tail probability
Non-superiority:
\(H_0\): \(\theta \geq b\)
\(H_1\): \(\theta < b\)
\(t=(\theta - b)/\sigma_\theta\)
p: Lower-tail probability
Equivalence: Two One-Sided Tests (TOST)
p: Maximum of the non-inferiority and non-superiority p values.
Thanks to Russell V. Lenth for the excellent emmeans
package and documentation which inspired this feature.
The type
argument determines the scale of the predictions used to compute quantities of interest with functions from the marginaleffects
package. Admissible values for type
depend on the model object. When users specify an incorrect value for type
, marginaleffects
will raise an informative error with a list of valid type
values for the specific model object. The first entry in the list in that error message is the default type.
The invlink(link)
is a special type defined by marginaleffects
. It is available for some (but not all) models and functions. With this link type, we first compute predictions on the link scale, then we use the inverse link function to backtransform the predictions to the response scale. This is useful for models with non-linear link functions as it can ensure that confidence intervals stay within desirable bounds, ex: 0 to 1 for a logit model. Note that an average of estimates with type="invlink(link)"
will not always be equivalent to the average of estimates with type="response"
.
Some of the most common type
values are:
response, link, E, Ep, average, class, conditional, count, cum.prob, cumprob, density, disp, ev, expected, expvalue, fitted, invlink(link), latent, linear.predictor, linpred, location, lp, mean, numeric, p, ppd, pr, precision, prediction, prob, probability, probs, quantile, risk, scale, survival, unconditional, utility, variance, xb, zero, zlink, zprob
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 newdata
arguments, or all combinations of the
categorical variables used to fit the model if newdata
is NULL
.
In the prediction grid, numeric variables are held at their means.
After constructing the grid and filling the grid with adjusted predictions,
marginal_means
computes marginal means for the variables listed in the
variables
argument, by average across all categories in the grid.
marginal_means
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://marginaleffects.com/
Greenland S. 2019. "Valid P-Values Behave Exactly as They Should: Some Misleading Criticisms of P-Values and Their Resolution With S-Values." The American Statistician. 73(S1): 106–114.
Cole, Stephen R, Jessie K Edwards, and Sander Greenland. 2020. "Surprise!" American Journal of Epidemiology 190 (2): 191–93. https://doi.org/10.1093/aje/kwaa136
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)
marginal_means(
mod,
variables = "cyl")
# collapse levels of cyl by averaging
by <- data.frame(
cyl = c(4, 6, 8),
by = c("4 & 6", "4 & 6", "8"))
marginal_means(mod,
variables = "cyl",
by = by)
# pairwise differences between collapsed levels
marginal_means(mod,
variables = "cyl",
by = by,
hypothesis = "pairwise")
# cross
marginal_means(mod,
variables = c("cyl", "carb"),
cross = TRUE)
# collapsed cross
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
marginal_means(mod)
# 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)
marginal_means(mod, variables = "carb", hypothesis = "b2 = b1")
marginal_means(mod, variables = "carb", hypothesis = lc)
# 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")))
marginal_means(mod, variables = "carb", hypothesis = lc)
Run the code above in your browser using DataLab