predictions {marginaleffects} | R Documentation |
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:
predictions(
model,
newdata = NULL,
variables = NULL,
vcov = TRUE,
conf_level = 0.95,
type = NULL,
by = FALSE,
byfun = NULL,
wts = NULL,
transform_post = NULL,
hypothesis = NULL,
df = Inf,
...
)
avg_predictions(
model,
newdata = NULL,
variables = NULL,
vcov = TRUE,
conf_level = 0.95,
type = NULL,
by = TRUE,
byfun = NULL,
wts = NULL,
transform_post = NULL,
hypothesis = NULL,
df = Inf,
...
)
model |
Model object |
newdata |
Grid of predictor values at which we evaluate predictions.
|
variables |
Counterfactual variables.
|
vcov |
Type of uncertainty estimates to report (e.g., for robust standard errors). Acceptable values:
|
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 |
by |
Aggregate unit-level estimates (aka, marginalize, average over). Valid inputs:
|
byfun |
A function such as |
wts |
string or numeric: weights to use when computing average
contrasts or slopes. These weights only affect the averaging in
|
transform_post |
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 numeric value, vector, or matrix, a string, or a string formula.
|
df |
Degrees of freedom used to compute p values and confidence intervals. A single numeric value between 1 and |
... |
Additional arguments are passed to the |
The newdata
argument, the tidy()
function, and datagrid()
function can be used to control the kind of predictions to report:
Average Predictions
Predictions at the Mean
Predictions at User-Specified values (aka Predictions at Representative values).
For glm()
or gam::gam()
models with type=NULL
(the default), predictions()
first predicts on the link scale, and then backtransforms the estimates and confidence intervals. This implies that the estimate
produced by avg_predictions()
will not be exactly equal to the average of the estimate
column produced by predictions()
. Users can circumvent this behavior and average predictions directly on the response scale by setting type="response"
explicitly. With type="response"
, the intervals are symmetric and may have undesirable properties (e.g., stretching beyond the [0,1]
bounds for a binary outcome regression).
A data.frame
with one row per observation and several columns:
rowid
: row number of the newdata
data frame
type
: prediction type, as defined by the type
argument
group
: (optional) value of the grouped outcome (e.g., categorical outcome models)
estimate
: predicted outcome
std.error
: standard errors computed using the delta method.
conf.low
: lower bound of the confidence interval (or equal-tailed interval for bayesian models)
conf.high
: upper bound of the confidence interval (or equal-tailed interval for bayesian models)
See ?print.marginaleffects
for printing options.
avg_predictions()
: Average predictions
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://vincentarelbundock.github.io/marginaleffects/articles/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://vincentarelbundock.github.io/marginaleffects/articles/bootstrap.html
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 | ||
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).
# 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
predictions(nom, type = "probs") |> head()
# 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)