Outcome predicted by a fitted model on a specified scale for a given combination of values of the predictor variables, such as their observed values, their means, or factor levels (a.k.a. "reference grid").
predictions(): unit-level (conditional) estimates.avg_predictions(): average (marginal) estimates.
The newdata argument and the datagrid() function can be used to control where statistics are evaluated in the predictor space: "at observed values", "at the mean", "at representative values", etc.
See the predictions vignette and package website for worked examples and case studies:
Usage
predictions(
model,
newdata = NULL,
variables = NULL,
vcov = TRUE,
conf_level = 0.95,
type = NULL,
by = FALSE,
byfun = NULL,
wts = FALSE,
transform = NULL,
hypothesis = NULL,
equivalence = NULL,
df = Inf,
numderiv = "fdforward",
...
)
avg_predictions(
model,
newdata = NULL,
variables = NULL,
vcov = TRUE,
conf_level = 0.95,
type = NULL,
by = TRUE,
byfun = NULL,
wts = FALSE,
transform = NULL,
hypothesis = NULL,
equivalence = NULL,
df = Inf,
numderiv = "fdforward",
...
)Arguments
- model
Model object
- newdata
Grid of predictor values at which we evaluate predictions.
Warning: Please avoid modifying your dataset between fitting the model and calling a
marginaleffectsfunction. This can sometimes lead to unexpected results.NULL(default): Unit-level predictions for each observed value in the dataset (empirical distribution). The dataset is retrieved usinginsight::get_data(), which tries to extract data from the environment. This may produce unexpected results if the original data frame has been altered since fitting the model.string:
"mean": Predictions evaluated when each predictor is held at its mean or mode.
"median": Predictions evaluated when each predictor is held at its median or mode.
"balanced": Predictions evaluated on a balanced grid with every combination of categories and numeric variables held at their means.
"tukey": Predictions evaluated at Tukey's 5 numbers.
"grid": Predictions evaluated on a grid of representative numbers (Tukey's 5 numbers and unique values of categorical predictors).
datagrid()call to specify a custom grid of regressors. For example:newdata = datagrid(cyl = c(4, 6)):cylvariable equal to 4 and 6 and other regressors fixed at their means or modes.See the Examples section and the
datagrid()documentation.
subset()call with a single argument to select a subset of the dataset used to fit the model, ex:newdata = subset(treatment == 1)dplyr::filter()call with a single argument to select a subset of the dataset used to fit the model, ex:newdata = filter(treatment == 1)
- variables
Counterfactual variables.
Output:
predictions(): The entire dataset is replicated once for each unique combination ofvariables, and predictions are made.avg_predictions(): The entire dataset is replicated, predictions are made, and they are marginalized byvariablescategories.Warning: This can be expensive in large datasets.
Warning: Users who need "conditional" predictions should use the
newdataargument instead ofvariables.
Input:
NULL: computes one prediction per row ofnewdataCharacter vector: the dataset is replicated once of every combination of unique values of the variables identified in
variables.Named list: names identify the subset of variables of interest and their values. For numeric variables, the
variablesargument supports functions and string shortcuts:A function which returns a numeric value
Numeric vector: Contrast between the 2nd element and the 1st element of the
xvector."iqr": Contrast across the interquartile range of the regressor.
"sd": Contrast across one standard deviation around the regressor mean.
"2sd": Contrast across two standard deviations around the regressor mean.
"minmax": Contrast between the maximum and the minimum values of the regressor.
"threenum": mean and 1 standard deviation on both sides
"fivenum": Tukey's five numbers
- 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::vcovHCHeteroskedasticity and autocorrelation consistent:
"HAC"Mixed-Models degrees of freedom: "satterthwaite", "kenward-roger"
Other:
"NeweyWest","KernHAC","OPG". See thesandwichpackage documentation."rsample", "boot", "fwb", and "simulation" are passed to the
methodargument of theinferences()function. To customize the bootstrap or simulation process, callinferences()directly.
One-sided formula which indicates the name of cluster variables (e.g.,
~unit_id). This formula is passed to theclusterargument of thesandwich::vcovCLfunction.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 contrasts or slopes. 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
typeisNULL, the first entry in the error message is used by default.- by
Aggregate unit-level estimates (aka, marginalize, average over). Valid inputs:
FALSE: return the original unit-level estimates.TRUE: aggregate estimates for each term.Character vector of column names in
newdataor in the data frame produced by calling the function without thebyargument.Data frame with a
bycolumn of group labels, and merging columns shared bynewdataor the data frame produced by calling the same function without thebyargument.See examples below.
For more complex aggregations, you can use the
FUNargument of thehypotheses()function. See that function's documentation and the Hypothesis Test vignettes on themarginaleffectswebsite.
- byfun
A function such as
mean()orsum()used to aggregate estimates within the subgroups defined by thebyargument.NULLuses themean()function. Must accept a numeric vector and return a single numeric value. This is sometimes used to take the sum or mean of predicted probabilities across outcome or predictor levels. See examples section.- wts
logical, string or numeric: weights to use when computing average predictions, contrasts or slopes. These weights only affect the averaging in
avg_*()or with thebyargument, and not unit-level estimates. See?weighted.meanstring: column name of the weights variable in
newdata. When supplying a column name towts, it is recommended to supply the original data (including the weights variable) explicitly tonewdata.numeric: vector of length equal to the number of rows in the original data or in
newdata(if supplied).FALSE: Equal weights.
TRUE: Extract weights from the fitted object with
insight::find_weights()and use them when taking weighted averages of estimates. Warning:newdata=datagrid()returns a single average weight, which is equivalent to usingwts=FALSE
- transform
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.
- hypothesis
specify a hypothesis test or custom contrast using a number , formula, string equation, vector, matrix, or function.
Number: The null hypothesis used in the computation of Z and p (before applying
transform).String: Equation to specify linear or non-linear hypothesis tests. Two-tailed tests must include an equal
=sign. One-tailed tests must start with<or>. If the terms incoef(object)uniquely identify estimates, they can be used in the formula. Otherwise, useb1,b2, etc. to identify the position of each parameter. Theb*wildcard can be used to test hypotheses on all estimates. When the hypothesis string represents a two-sided equation, theestimatecolumn holds the value of the left side minus the right side of the equation. If a named vector is used, the names are used as labels in the output. Examples:hp = drathp + drat = 12b1 + b2 + b3 = 0b* / b1 = 1<= 0>= -3.5b1 >= 10
Formula:
lhs ~ rhs | grouplhsratio(null = 1)difference(null = 0)Leave empty for default value
rhspairwiseandrevpairwise: 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.meandev: difference between an estimate and the mean of all estimates.`meanotherdev: difference between an estimate and the mean of all other estimates, excluding the current one.
poly: polynomial contrasts, as computed by thestats::contr.poly()function.helmert: Helmert contrasts, as computed by thestats::contr.helmert()function. Contrast 2nd level to the first, 3rd to the average of the first two, and so on.trt_vs_ctrl: difference between the mean of estimates (except the first) and the first estimate.I(fun(x)): custom function to manipulate the vector of estimatesx. The functionfun()can return multiple (potentially named) estimates.
group(optional)Column name of
newdata. Conduct hypothesis tests withing subsets of the data.
Examples:
~ poly~ sequential | groupid~ referenceratio ~ pairwisedifference ~ pairwise | groupid~ I(x - mean(x)) | groupid~ I(\(x) c(a = x[1], b = mean(x[2:3]))) | groupid
Matrix or Vector: Each column is a vector of weights. The the output is the dot product between these vectors of weights and the vector of estimates. The matrix can have column names to label the estimates.
Function:
Accepts an argument
x: object produced by amarginaleffectsfunction or a data frame with columnrowidandestimateReturns a data frame with columns
termandestimate(mandatory) androwid(optional).The function can also accept optional input arguments:
newdata,by,draws.This function approach will not work for Bayesian models or with bootstrapping. In those cases, it is easy to use
get_draws()to extract and manipulate the draws directly.
See the Examples section below and the vignette: https://marginaleffects.com/chapters/hypothesis.html
Warning: When calling
predictions()withtype="invlink(link)"(the default in some models),hypothesisis tested and p values are computed on the link scale.
- equivalence
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. For bayesian models, this report the proportion of posterior draws in the interval and the ROPE. See Details section below.
- df
Degrees of freedom used to compute p values and confidence intervals.
A single numeric value between 1 and
Inf, or a numeric vector with length equal to the number of rows in the output. WhendfisInf, the normal distribution is used. Whendfis finite, thetdistribution is used."residual": Calls insight::get_df to extract degrees of freedom from the model automatically.
"satterthwaite" or "kenward-roger": Use the Satterthwaite or Kenward-Roger approximation to compute degrees of freedom in mixed effects models.
- numderiv
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
numDerivargument, with the name of the method first and named arguments following, ex:numderiv=list("fdcenter", eps = 1e-5). When an unknown argument is used,marginaleffectsprints 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 themarginaleffectswebsite). 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?slopesdocumentation for a non-exhaustive list of available arguments.
Value
A data.frame with one row per estimate. This data frame is pretty-printed by default, but users can interact with it as a regular data frame, with functions like nrow(), head(), colnames(), etc. Values can be extracted using standard [,] or $ operators, and manipulated using external packages like dplyr or data.table.
Columns may include:
rowid: row number of thenewdatadata framegroup: (optional) value of the grouped outcome (e.g., categorical outcome models)term: the focal variable.estimate: an estimate of the prediction, counterfactual comparison, or slope.std.error: standard errors computed via the delta method.p.value: p value associated to theestimatecolumn. The null is determined by thehypothesisargument (0 by default).s.value: Shannon information transforms of p values. See the S values vignette at https://marginaleffects.com the marginaleffects website.conf.low: lower bound of the confidence (or credible) interval defined by theconf_levelargument.conf.high: upper bound of the confidence (or credible) interval defined by theconf_levelargument.predicted_lo: predicted outcome for the "low" value of the focal predictor in a counterfactual comparison.predicted_hi: predicted outcome for the "high" value of the focal predictor in a counterfactual comparison.p.rope.unconditional: share of posterior draws in the interval specified by theequivalenceargument. This is only available for Bayesian models.p.rope.conditional: share of posterior draws in the interval specified by theequivalenceargument, among draws in the confidence interval. This is only available for Bayesian models.rope: share of the posterior draws betweenconf.lowandconf.highthat are covered by the interval specified by theequivalenceargument.statistic.noninf: test statistic for non-inferiority test (whenequivalenceargument is used).statistic.nonsup: test statistic for non-superiority test (whenequivalenceargument is used).p.value.noninf: p-value for non-inferiority test (whenequivalenceargument is used).p.value.nonsup: p-value for non-superiority test (whenequivalenceargument is used).p.value.equiv: p-value for equivalence test using Two One-Sided Tests (TOST) approach (whenequivalenceargument is used).
See ?print.marginaleffects for printing options.
The data.frames produced by marginaleffects stores an attribute that holds many internal objects, such as the original model, data, and much other information that can be used for post-processing. This information can be inspected using the components() function.
Warning: The internal attributes retrieved by components() are not considered part of the public API of the package. Their names and contents can change without warning or notice. Users should not rely on them.
Warning: In some cases, the internal attributes used by marginaleffects() can use up a substantial amount of memory. To clear this data, use the prune() function or set options(marginaleffects_lean=TRUE).
Standard errors using the delta method
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 "Uncertainty" chapter on the marginaleffects website for more details on the computation of standard errors, bootstrapping, and more:
https://marginaleffects.com/chapters/uncertainty.html
Model-Specific Arguments
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 |
gam | exclude | mgcv::predict.gam | |
robustlmm | rlmerMod | re.form | robustlmm::predict.rlmerMod |
allow.new.levels | robustlmm::predict.rlmerMod | ||
MCMCglmm | MCMCglmm | ndraws | |
sampleSelection | selection | part | sampleSelection::predict.selection |
Bayesian posterior summaries
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).
Equivalence, Inferiority, Superiority
\(\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.
Prediction types
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 only for the predictions() function. 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". This type is default when calling predictions(). It is available—but not default—when calling avg_predictions() or predictions() with the by argument.
Some of the most common type values are:
response, link, E, Ep, average, class, conditional, count, cum.prob, cumhaz, cumprob, density, detection, disp, ev, expected, expvalue, fitted, hazard, invlink(link), latent, latent_N, linear, linear.predictor, linpred, location, lp, mean, numeric, p, posterior, ppd, pr, precision, prediction, prob, probability, probs, quantile, risk, rmst, scale, survival, unconditional, utility, variance, xb, zero, zlink, zprob
Order of operations
Behind the scenes, the arguments of marginaleffects functions are evaluated in this order:
newdatavariablescomparisonandslopebyvcovhypothesistransform
Parallel computation
The slopes() and comparisons() functions can use parallelism to
speed up computation. Operations are parallelized for the computation of
standard errors, at the model coefficient level. There is always
considerable overhead when using parallel computation, mainly involved
in passing the whole dataset to the different processes. Thus, parallel
computation is most likely to be useful when the model includes many parameters
and the dataset is relatively small.
Warning: In many cases, parallel processing will not be useful at all.
To activate parallel computation, users must load the future.apply package,
call plan() function, and set a global option.
options(marginaleffects_parallel = TRUE): parallelize delta method computation of standard errors.
options(marginaleffects_parallel_inferences = TRUE): parallelize "rsample" or "fwb" bootstrap computation in inferences().
options(marginaleffects_parallel_packages = TRUE): vector of strings with the names of modeling packages used to fit the model, ex: c("survival", "splines")
For example:
library(future.apply)
plan("multisession", workers = 4)
options(marginaleffects_parallel = FALSE)
options(marginaleffects_parallel_inferences = TRUE)
options(marginaleffects_parallel_packages = c("survival", "splines"))
slopes(model)To disable parallelism in marginaleffects altogether, you can set a global option:
options(marginaleffects_parallel = FALSE)Global options
The behavior of marginaleffects functions can be modified by setting global options.
Disable some safety checks and warnings:
options(marginaleffects_startup_message = FALSE)Disable the startup message printed on
library(marginaleffects).
options(marginaleffects_safe = FALSE)Disable safety checks and warnings.
options(marginaleffects_print_omit = c("p.value", "s.value"))Omit some columns from the printed output.
Enforce lean return objects, sans information about the original model and data, and other ancillary attributes. Note that this will disable some advanced post-processing features and functions like hypotheses.
options(marginaleffects_lean = TRUE)Other options:
marginaleffects_plot_gray: logical. IfTRUE, the default color of the plot is gray. Default isFALSE.
References
Arel-Bundock V, Greifer N, Heiss A (2024). “How to Interpret Statistical Models Using marginaleffects for R and Python.” Journal of Statistical Software, 111(9), 1-32. doi:10.18637/jss.v111.i09 doi:10.18637/jss.v111.i09
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. doi:10.1093/aje/kwaa136
Examples
if (FALSE) { # interactive() || isTRUE(Sys.getenv("R_DOC_BUILD") == "true")
library("marginaleffects")
# Adjusted Prediction for every row of the original dataset
mod <- lm(mpg ~ hp + factor(cyl), data = mtcars)
pred <- predictions(mod)
head(pred)
# Adjusted Predictions at User-Specified Values of the Regressors
predictions(mod, newdata = datagrid(hp = c(100, 120), cyl = 4))
m <- lm(mpg ~ hp + drat + factor(cyl) + factor(am), data = mtcars)
predictions(m, newdata = datagrid(FUN_factor = unique, FUN_numeric = median))
# Average Adjusted Predictions (AAP)
library(dplyr)
mod <- lm(mpg ~ hp * am * vs, mtcars)
avg_predictions(mod)
predictions(mod, by = "am")
# Conditional Adjusted Predictions
plot_predictions(mod, condition = "hp")
# Counterfactual predictions with the `variables` argument
# the `mtcars` dataset has 32 rows
mod <- lm(mpg ~ hp + am, data = mtcars)
p <- predictions(mod)
head(p)
nrow(p)
# average counterfactual predictions
avg_predictions(mod, variables = "am")
# counterfactual predictions obtained by replicating the entire for different
# values of the predictors
p <- predictions(mod, variables = list(hp = c(90, 110)))
nrow(p)
# hypothesis test: is the prediction in the 1st row equal to the prediction in the 2nd row
mod <- lm(mpg ~ wt + drat, data = mtcars)
predictions(
mod,
newdata = datagrid(wt = 2:3),
hypothesis = "b1 = b2")
# same hypothesis test using row indices
predictions(
mod,
newdata = datagrid(wt = 2:3),
hypothesis = "b1 - b2 = 0")
# same hypothesis test using numeric vector of weights
predictions(
mod,
newdata = datagrid(wt = 2:3),
hypothesis = c(1, -1))
# two custom contrasts using a matrix of weights
lc <- matrix(
c(
1, -1,
2, 3),
ncol = 2)
predictions(
mod,
newdata = datagrid(wt = 2:3),
hypothesis = lc)
# `by` argument
mod <- lm(mpg ~ hp * am * vs, data = mtcars)
predictions(mod, by = c("am", "vs"))
library(nnet)
nom <- multinom(factor(gear) ~ mpg + am * vs, data = mtcars, trace = FALSE)
# first 5 raw predictions
p <- predictions(nom, type = "probs")
head(p)
# average predictions
avg_predictions(nom, type = "probs", by = "group")
by <- data.frame(
group = c("3", "4", "5"),
by = c("3,4", "3,4", "5"))
predictions(nom, type = "probs", by = by)
# sum of predicted probabilities for combined response levels
mod <- multinom(factor(cyl) ~ mpg + am, data = mtcars, trace = FALSE)
by <- data.frame(
by = c("4,6", "4,6", "8"),
group = as.character(c(4, 6, 8)))
predictions(mod, newdata = "mean", byfun = sum, by = by)
}