comparisons {marginaleffects} | R Documentation |
Predict the outcome variable at different regressor values (e.g., college
graduates vs. others), and compare those predictions by computing a difference,
ratio, or some other function. comparisons()
can return many quantities of
interest, such as contrasts, differences, risk ratios, changes in log odds,
slopes, elasticities, etc.
comparisons()
: unit-level (conditional) estimates.
avg_comparisons()
: average (marginal) estimates.
variables
identifies the focal regressors whose "effect" we are interested in. comparison
determines how predictions with different regressor values are compared (difference, ratio, odds, etc.). The newdata
argument and the datagrid()
function control where statistics are evaluated in the predictor space: "at observed values", "at the mean", "at representative values", etc.
See the comparisons vignette and package website for worked examples and case studies:
comparisons( model, newdata = NULL, variables = NULL, comparison = "difference", type = NULL, vcov = TRUE, by = FALSE, conf_level = 0.95, transform = NULL, cross = FALSE, wts = NULL, hypothesis = NULL, equivalence = NULL, p_adjust = NULL, df = Inf, eps = NULL, ... ) avg_comparisons( model, newdata = NULL, variables = NULL, type = NULL, vcov = TRUE, by = TRUE, conf_level = 0.95, comparison = "difference", transform = NULL, cross = FALSE, wts = NULL, hypothesis = NULL, equivalence = NULL, p_adjust = NULL, df = Inf, eps = NULL, ... )
model |
Model object |
newdata |
Grid of predictor values at which we evaluate the comparisons.
|
variables |
Focal variables
|
comparison |
How should pairs of predictions be compared? Difference, ratio, odds ratio, or user-defined functions.
|
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 |
vcov |
Type of uncertainty estimates to report (e.g., for robust standard errors). Acceptable values:
|
by |
Aggregate unit-level estimates (aka, marginalize, average over). Valid inputs:
|
conf_level |
numeric value between 0 and 1. Confidence level to use to build a confidence interval. |
transform |
string or function. Transformation applied to unit-level estimates and confidence intervals just before the function returns results. Functions must accept a vector and return a vector of the same length. Support string shortcuts: "exp", "ln" |
cross |
|
wts |
string or numeric: weights to use when computing average
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, or a string formula.
|
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 |
eps |
NULL or numeric value which determines the step size to use when
calculating numerical derivatives: (f(x+eps)-f(x))/eps. When |
... |
Additional arguments are passed to the |
A data.frame
with one row per observation (per term/group) 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)
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 the estimate
column. The null is determined by the hypothesis
argument (0 by default), and p values are computed before applying the transform
argument.
See ?print.marginaleffects
for printing options.
avg_comparisons()
: Average comparisons
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. 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 | |
The following transformations can be applied by supplying one of the shortcut strings to the
comparison
argument.
hi
is a vector of adjusted predictions for the "high" side of the
contrast. lo
is a vector of adjusted predictions for the "low" side of the
contrast. y
is a vector of adjusted predictions for the original data. x
is the predictor in the original data. eps
is the step size to use to
compute derivatives and elasticities.
Shortcut | Function |
difference | \(hi, lo) hi - lo |
differenceavg | \(hi, lo) mean(hi) - mean(lo) |
dydx | \(hi, lo, eps) (hi - lo)/eps |
eyex | \(hi, lo, eps, y, x) (hi - lo)/eps * (x/y) |
eydx | \(hi, lo, eps, y, x) ((hi - lo)/eps)/y |
dyex | \(hi, lo, eps, x) ((hi - lo)/eps) * x |
dydxavg | \(hi, lo, eps) mean((hi - lo)/eps) |
eyexavg | \(hi, lo, eps, y, x) mean((hi - lo)/eps * (x/y)) |
eydxavg | \(hi, lo, eps, y, x) mean(((hi - lo)/eps)/y) |
dyexavg | \(hi, lo, eps, x) mean(((hi - lo)/eps) * x) |
ratio | \(hi, lo) hi/lo |
ratioavg | \(hi, lo) mean(hi)/mean(lo) |
lnratio | \(hi, lo) log(hi/lo) |
lnratioavg | \(hi, lo) log(mean(hi)/mean(lo)) |
lnor | \(hi, lo) log((hi/(1 - hi))/(lo/(1 - lo))) |
lnoravg | \(hi, lo) log((mean(hi)/(1 - mean(hi)))/(mean(lo)/(1 - mean(lo)))) |
expdydx | \(hi, lo, eps) ((exp(hi) - exp(lo))/exp(eps))/eps |
expdydxavg | \(hi, lo, eps) mean(((exp(hi) - exp(lo))/exp(eps))/eps) |
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).
θ is an estimate, σ_θ its estimated standard error, and [a, b] are the bounds of the interval supplied to the equivalence
argument.
Non-inferiority:
H0: θ <= a
H1: θ > a
t=(θ - a)/σ_θ
p: Upper-tail probability
Non-superiority:
H0: θ >= b
H1: θ < b
t=(θ - b)/σ_θ
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.
## Not run: library(marginaleffects) # Linear model tmp <- mtcars tmp$am <- as.logical(tmp$am) mod <- lm(mpg ~ am + factor(cyl), tmp) avg_comparisons(mod, variables = list(cyl = "reference")) avg_comparisons(mod, variables = list(cyl = "sequential")) avg_comparisons(mod, variables = list(cyl = "pairwise")) # GLM with different scale types mod <- glm(am ~ factor(gear), data = mtcars) avg_comparisons(mod, type = "response") avg_comparisons(mod, type = "link") # Contrasts at the mean comparisons(mod, newdata = "mean") # Contrasts between marginal means comparisons(mod, newdata = "marginalmeans") # Contrasts at user-specified values comparisons(mod, newdata = datagrid(am = 0, gear = tmp$gear)) comparisons(mod, newdata = datagrid(am = unique, gear = max)) m <- lm(mpg ~ hp + drat + factor(cyl) + factor(am), data = mtcars) comparisons(m, variables = "hp", newdata = datagrid(FUN_factor = unique, FUN_numeric = median)) # Numeric contrasts mod <- lm(mpg ~ hp, data = mtcars) avg_comparisons(mod, variables = list(hp = 1)) avg_comparisons(mod, variables = list(hp = 5)) avg_comparisons(mod, variables = list(hp = c(90, 100))) avg_comparisons(mod, variables = list(hp = "iqr")) avg_comparisons(mod, variables = list(hp = "sd")) avg_comparisons(mod, variables = list(hp = "minmax")) # using a function to specify a custom difference in one regressor dat <- mtcars dat$new_hp <- 49 * (dat$hp - min(dat$hp)) / (max(dat$hp) - min(dat$hp)) + 1 modlog <- lm(mpg ~ log(new_hp) + factor(cyl), data = dat) fdiff <- \(x) data.frame(x, x + 10) avg_comparisons(modlog, variables = list(new_hp = fdiff)) # Adjusted Risk Ratio: see the contrasts vignette mod <- glm(vs ~ mpg, data = mtcars, family = binomial) avg_comparisons(mod, comparison = "lnratioavg", transform = exp) # Adjusted Risk Ratio: Manual specification of the `comparison` avg_comparisons( mod, comparison = function(hi, lo) log(mean(hi) / mean(lo)), transform = exp) # cross contrasts mod <- lm(mpg ~ factor(cyl) * factor(gear) + hp, data = mtcars) avg_comparisons(mod, variables = c("cyl", "gear"), cross = TRUE) # variable-specific contrasts avg_comparisons(mod, variables = list(gear = "sequential", hp = 10)) # hypothesis test: is the `hp` marginal effect at the mean equal to the `drat` marginal effect mod <- lm(mpg ~ wt + drat, data = mtcars) comparisons( mod, newdata = "mean", hypothesis = "wt = drat") # same hypothesis test using row indices comparisons( mod, newdata = "mean", hypothesis = "b1 - b2 = 0") # same hypothesis test using numeric vector of weights comparisons( mod, newdata = "mean", hypothesis = c(1, -1)) # two custom contrasts using a matrix of weights lc <- matrix(c( 1, -1, 2, 3), ncol = 2) comparisons( mod, newdata = "mean", hypothesis = lc) # `by` argument mod <- lm(mpg ~ hp * am * vs, data = mtcars) comparisons(mod, by = TRUE) mod <- lm(mpg ~ hp * am * vs, data = mtcars) avg_comparisons(mod, variables = "hp", by = c("vs", "am")) library(nnet) mod <- multinom(factor(gear) ~ mpg + am * vs, data = mtcars, trace = FALSE) by <- data.frame( group = c("3", "4", "5"), by = c("3,4", "3,4", "5")) comparisons(mod, type = "probs", by = by) ## End(Not run)