library("marginaleffects")
# Unit-level (conditional) Marginal Effects
mod <- glm(am ~ hp * wt, data = mtcars, family = binomial)
mfx <- slopes(mod)
head(mfx)
# Average Marginal Effect (AME)
avg_slopes(mod, by = TRUE)
# Marginal Effect at the Mean (MEM)
slopes(mod, newdata = datagrid())
# Marginal Effect at User-Specified Values
# Variables not explicitly included in `datagrid()` are held at their means
slopes(mod, newdata = datagrid(hp = c(100, 110)))
# Group-Average Marginal Effects (G-AME)
# Calculate marginal effects for each observation, and then take the average
# marginal effect within each subset of observations with different observed
# values for the `cyl` variable:
mod2 <- lm(mpg ~ hp * cyl, data = mtcars)
avg_slopes(mod2, variables = "hp", by = "cyl")
# Marginal Effects at User-Specified Values (counterfactual)
# Variables not explicitly included in `datagrid()` are held at their
# original values, and the whole dataset is duplicated once for each
# combination of the values in `datagrid()`
mfx <- slopes(mod,
newdata = datagrid(
hp = c(100, 110),
grid_type = "counterfactual"))
head(mfx)
# Heteroskedasticity robust standard errors
mfx <- slopes(mod, vcov = sandwich::vcovHC(mod))
head(mfx)
# hypothesis test: is the `hp` marginal effect at the mean equal to the `drat` marginal effect
mod <- lm(mpg ~ wt + drat, data = mtcars)
slopes(
mod,
newdata = "mean",
hypothesis = "wt = drat")
# same hypothesis test using row indices
slopes(
mod,
newdata = "mean",
hypothesis = "b1 - b2 = 0")
# same hypothesis test using numeric vector of weights
slopes(
mod,
newdata = "mean",
hypothesis = c(1, -1))
# two custom contrasts using a matrix of weights
lc <- matrix(
c(
1, -1,
2, 3),
ncol = 2)
colnames(lc) <- c("Contrast A", "Contrast B")
slopes(
mod,
newdata = "mean",
hypothesis = lc)
Slopes (aka Partial derivatives, Marginal Effects, or Trends)
Description
Partial derivative of the regression equation with respect to a regressor of interest.
-
slopes()
: unit-level (conditional) estimates. -
avg_slopes()
: 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 slopes vignette and package website for worked examples and case studies:
Usage
slopes(
model,
newdata = NULL,
variables = NULL,
type = NULL,
by = FALSE,
vcov = TRUE,
conf_level = 0.95,
slope = "dydx",
wts = FALSE,
hypothesis = NULL,
equivalence = NULL,
p_adjust = NULL,
df = Inf,
eps = NULL,
numderiv = "fdforward",
...
)
avg_slopes(
model,
newdata = NULL,
variables = NULL,
type = NULL,
by = TRUE,
vcov = TRUE,
conf_level = 0.95,
slope = "dydx",
wts = FALSE,
hypothesis = NULL,
equivalence = NULL,
p_adjust = NULL,
df = Inf,
eps = NULL,
numderiv = "fdforward",
...
)
Arguments
model
|
Model object |
newdata
|
Grid of predictor values at which we evaluate the slopes.
|
variables
|
Focal variables
|
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 type is NULL , the first entry in the error message is used by default.
|
by
|
Aggregate unit-level estimates (aka, marginalize, average over). Valid inputs:
|
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. |
slope
|
string indicates the type of slope or (semi-)elasticity to compute:
|
wts
|
logical, string or numeric: weights to use when computing average predictions, contrasts or slopes. These weights only affect the averaging in
|
hypothesis
|
specify a hypothesis test or custom contrast using a numeric value, vector, or matrix; a string equation; string; a formula, or a function.
|
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. See Details section below. |
p_adjust
|
Adjust p-values for multiple comparisons: "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", or "fdr". See stats::p.adjust |
df
|
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))
|
eps
|
NULL or numeric value which determines the step size to use when calculating numerical derivatives: (f(x+eps)-f(x))/eps. When eps is NULL , the step size is 0.0001 multiplied by the difference between the maximum and minimum values of the variable with respect to which we are taking the derivative. Changing eps may be necessary to avoid numerical problems in certain 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.
|
…
|
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 ?slopes documentation for a non-exhaustive list of available arguments.
|
Details
A "slope" or "marginal effect" is the partial derivative of the regression equation with respect to a variable in the model. This function uses automatic differentiation to compute slopes for a vast array of models, including non-linear models with transformations (e.g., polynomials). Uncertainty estimates are computed using the delta method.
Numerical derivatives for the slopes
function are calculated using a simple epsilon difference approach: \(\partial Y / \partial X = (f(X + \varepsilon/2) - f(X-\varepsilon/2)) / \varepsilon\), where f is the predict()
method associated with the model class, and \(\varepsilon\) is determined by the eps
argument.
Value
A data.frame
with one row per observation (per term/group) and several columns:
-
rowid
: row number of thenewdata
data frame -
type
: prediction type, as defined by thetype
argument -
group
: (optional) value of the grouped outcome (e.g., categorical outcome models) -
term
: the variable whose marginal effect is computed -
dydx
: slope of the outcome with respect to the term, for a given combination of predictor values -
std.error
: standard errors computed by via the delta method. -
p.value
: p value associated to theestimate
column. The null is determined by thehypothesis
argument (0 by default), and p values are computed before applying thetransform
argument. For models of classfeglm
,Gam
,glm
andnegbin
, p values are computed on the link scale by default unless thetype
argument is specified explicitly. -
s.value
: Shannon information transforms of p values. How many consecutive "heads" tosses would provide the same amount of evidence (or "surprise") against the null hypothesis that the coin is fair? The purpose of S is to calibrate the analyst’s intuition about the strength of evidence encoded in p against a well-known physical phenomenon. See Greenland (2019) and Cole et al. (2020). -
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.
Functions
-
avg_slopes()
: Average slopes
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 "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
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, ppd, pr, precision, prediction, prob, probability, probs, quantile, risk, rmst, scale, survival, unconditional, utility, variance, xb, zero, zlink, zprob
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. For example:
library(future.apply) plan("multicore", workers = 4) options(marginaleffects_parallel = TRUE) slopes(model)
To disable parallelism in marginaleffects
altogether, you can set a global option:
options(marginaleffects_parallel = FALSE)
Order of operations
Behind the scenes, the arguments of marginaleffects
functions are evaluated in this order:
-
newdata
-
variables
-
comparison
andslopes
-
by
-
vcov
-
hypothesis
-
transform
Global options
The behavior of marginaleffects
functions can be modified by setting global options.
Disable some safety checks:
options(marginaleffects_safe = FALSE)
Omit some columns from the printed output:
options(marginaleffects_print_omit = c("p.value", "s.value"))`
References
-
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