Comparisons Between Predictions Made With Different Regressor Values

Description

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, lift, 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:

Usage

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,
  numderiv = "fdforward",
  ...
)

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,
  numderiv = "fdforward",
  ...
)

Arguments

model Model object
newdata

Grid of predictor values at which we evaluate the comparisons.

  • Warning: Please avoid modifying your dataset between fitting the model and calling a marginaleffects function. This can sometimes lead to unexpected results.

  • NULL (default): Unit-level contrasts for each observed value in the dataset (empirical distribution). The dataset is retrieved using insight::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.

  • data frame: Unit-level contrasts for each row of the newdata data frame.

  • string:

    • "mean": Contrasts at the Mean. Contrasts when each predictor is held at its mean or mode.

    • "median": Contrasts at the Median. Contrasts when each predictor is held at its median or mode.

    • "marginalmeans": Contrasts at Marginal Means.

    • "tukey": Contrasts at Tukey’s 5 numbers.

    • "grid": Contrasts 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)): cyl variable equal to 4 and 6 and other regressors fixed at their means or modes.

    • newdata = datagrid(mpg = fivenum): mpg variable held at Tukey’s five numbers (using the fivenum function), and other regressors fixed at their means or modes.

    • See the Examples section and the datagrid documentation.

variables

Focal variables

  • NULL: compute comparisons for all the variables in the model object (can be slow).

  • Character vector: subset of variables (usually faster).

  • Named list: names identify the subset of variables of interest, and values define the type of contrast to compute. Acceptable values depend on the variable type:

    • Factor or character variables:

      • "reference": Each factor level is compared to the factor reference (base) level

      • "all": All combinations of observed levels

      • "sequential": Each factor level is compared to the previous factor level

      • "pairwise": Each factor level is compared to all other levels

      • "minmax": The highest and lowest levels of a factor.

      • "revpairwise", "revreference", "revsequential": inverse of the corresponding hypotheses.

      • Vector of length 2 with the two values to compare.

      • Data frame with the same number of rows as newdata, with two columns of "lo" and "hi" values to compare.

      • Function that accepts a vector and returns a data frame with two columns of "lo" and "hi" values to compare. See examples below.

    • Logical variables:

      • NULL: contrast between TRUE and FALSE

      • Data frame with the same number of rows as newdata, with two columns of "lo" and "hi" values to compare.

      • Function that accepts a vector and returns a data frame with two columns of "lo" and "hi" values to compare. See examples below.

    • Numeric variables:

      • Numeric of length 1: Forward contrast for a gap of x, computed between the observed value and the observed value plus x. Users can set a global option to get a "center" or "backward" contrast instead: options(marginaleffects_contrast_direction=“center”)

      • Numeric vector of length 2: Contrast between the largest and the smallest elements of the x vector.

      • Data frame with the same number of rows as newdata, with two columns of "lo" and "hi" values to compare.

      • Function that accepts a vector and returns a data frame with two columns of "lo" and "hi" values to compare. See examples below.

      • "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.

    • Examples:

      • variables = list(gear = “pairwise”, hp = 10)

      • variables = list(gear = “sequential”, hp = c(100, 120))

      • variables = list(hp = (x) data.frame(low = x - 5, high = x + 10))

      • See the Examples section below for more.

comparison

How should pairs of predictions be compared? Difference, ratio, odds ratio, or user-defined functions.

  • string: shortcuts to common contrast functions.

    • Supported shortcuts strings: difference, differenceavg, differenceavgwts, dydx, eyex, eydx, dyex, dydxavg, eyexavg, eydxavg, dyexavg, dydxavgwts, eyexavgwts, eydxavgwts, dyexavgwts, ratio, ratioavg, ratioavgwts, lnratio, lnratioavg, lnratioavgwts, lnor, lnoravg, lnoravgwts, lift, liftavg, expdydx, expdydxavg, expdydxavgwts

    • See the Comparisons section below for definitions of each transformation.

  • function: accept two equal-length numeric vectors of adjusted predictions (hi and lo) and returns a vector of contrasts of the same length, or a unique numeric value.

    • See the Transformations section below for examples of valid 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 type is NULL, the first entry in the error message is used by default.
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::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))

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 newdata or in the data frame produced by calling the function without the by argument.

  • 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.

  • See examples below.

  • For more complex aggregations, you can use the FUN argument of the hypotheses() function. See that function’s documentation and the Hypothesis Test vignettes on the marginaleffects website.

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
  • FALSE: Contrasts represent the change in adjusted predictions when one predictor changes and all other variables are held constant.

  • TRUE: Contrasts represent the changes in adjusted predictions when all the predictors specified in the variables argument are manipulated simultaneously (a "cross-contrast").

wts

string or numeric: weights to use when computing average contrasts or slopes. These weights only affect the averaging in avg_*() or with the by argument, and not the unit-level estimates themselves. Internally, estimates and weights are passed to the weighted.mean() function.

  • string: column name of the weights variable in newdata. When supplying a column name to wts, it is recommended to supply the original data (including the weights variable) explicitly to newdata.

  • numeric: vector of length equal to the number of rows in the original data or in newdata (if supplied).

hypothesis

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. If a named vector is used, the names are used as labels in the output. 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

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.

  • "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 ?slopes documentation for a non-exhaustive list of available arguments.

Value

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.

  • 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_comparisons(): Average comparisons

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
robustlmm rlmerMod re.form robustlmm::predict.rlmerMod
allow.new.levels robustlmm::predict.rlmerMod
MCMCglmm MCMCglmm ndraws

comparison argument functions

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 - 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))))
lift (hi, lo) (hi - lo)/lo
liftavg (hi, lo) (mean(hi - lo))/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)

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 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, detection, disp, ev, expected, expvalue, fitted, invlink(link), latent, latent_N, 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

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

Examples

library(marginaleffects)



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"))

 Term Contrast Estimate Std. Error     z Pr(>|z|)    S  2.5 % 97.5 %
  cyl    6 - 4    -6.16       1.54 -4.01   <0.001 14.0  -9.17  -3.15
  cyl    8 - 4   -10.07       1.45 -6.93   <0.001 37.8 -12.91  -7.22

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
avg_comparisons(mod, variables = list(cyl = "sequential"))

 Term Contrast Estimate Std. Error     z Pr(>|z|)    S 2.5 % 97.5 %
  cyl    6 - 4    -6.16       1.54 -4.01  < 0.001 14.0 -9.17  -3.15
  cyl    8 - 6    -3.91       1.47 -2.66  0.00781  7.0 -6.79  -1.03

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
avg_comparisons(mod, variables = list(cyl = "pairwise"))

 Term Contrast Estimate Std. Error     z Pr(>|z|)    S  2.5 % 97.5 %
  cyl    6 - 4    -6.16       1.54 -4.01  < 0.001 14.0  -9.17  -3.15
  cyl    8 - 4   -10.07       1.45 -6.93  < 0.001 37.8 -12.91  -7.22
  cyl    8 - 6    -3.91       1.47 -2.66  0.00781  7.0  -6.79  -1.03

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
# GLM with different scale types
mod <- glm(am ~ factor(gear), data = mtcars)
avg_comparisons(mod, type = "response")

 Term Contrast Estimate Std. Error    z Pr(>|z|)    S 2.5 % 97.5 %
 gear    4 - 3    0.667      0.117 5.68   <0.001 26.1 0.436  0.897
 gear    5 - 3    1.000      0.157 6.39   <0.001 32.5 0.693  1.307

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
avg_comparisons(mod, type = "link")

 Term Contrast Estimate Std. Error    z Pr(>|z|)    S 2.5 % 97.5 %
 gear    4 - 3    0.667      0.117 5.68   <0.001 26.1 0.436  0.897
 gear    5 - 3    1.000      0.157 6.39   <0.001 32.5 0.693  1.307

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  link 
# Contrasts at the mean
comparisons(mod, newdata = "mean")

 Term Contrast Estimate Std. Error    z Pr(>|z|)    S 2.5 % 97.5 % gear
 gear    4 - 3    0.667      0.117 5.68   <0.001 26.1 0.436  0.897    3
 gear    5 - 3    1.000      0.157 6.39   <0.001 32.5 0.693  1.307    3

Columns: rowid, term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high, predicted_lo, predicted_hi, predicted, am, gear 
Type:  response 
# Contrasts between marginal means
comparisons(mod, newdata = "marginalmeans")

 Term Contrast Estimate Std. Error    z Pr(>|z|)    S 2.5 % 97.5 %
 gear    4 - 3    0.667      0.117 5.68   <0.001 26.1 0.436  0.897
 gear    5 - 3    1.000      0.157 6.39   <0.001 32.5 0.693  1.307

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high, predicted_lo, predicted_hi, predicted 
Type:  response 
# Contrasts at user-specified values
comparisons(mod, newdata = datagrid(am = 0, gear = tmp$gear))

 Term Contrast gear Estimate Std. Error    z Pr(>|z|)    S 2.5 % 97.5 %
 gear    4 - 3    3    0.667      0.117 5.68   <0.001 26.1 0.436  0.897
 gear    4 - 3    4    0.667      0.117 5.68   <0.001 26.1 0.436  0.897
 gear    4 - 3    5    0.667      0.117 5.68   <0.001 26.1 0.436  0.897
 gear    5 - 3    3    1.000      0.157 6.39   <0.001 32.5 0.693  1.307
 gear    5 - 3    4    1.000      0.157 6.39   <0.001 32.5 0.693  1.307
 gear    5 - 3    5    1.000      0.157 6.39   <0.001 32.5 0.693  1.307

Columns: rowid, term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high, am, gear, predicted_lo, predicted_hi, predicted 
Type:  response 
comparisons(mod, newdata = datagrid(am = unique, gear = max))

 Term Contrast gear Estimate Std. Error    z Pr(>|z|)    S 2.5 % 97.5 %
 gear    4 - 3    5    0.667      0.117 5.68   <0.001 26.1 0.436  0.897
 gear    4 - 3    5    0.667      0.117 5.68   <0.001 26.1 0.436  0.897
 gear    5 - 3    5    1.000      0.157 6.39   <0.001 32.5 0.693  1.307
 gear    5 - 3    5    1.000      0.157 6.39   <0.001 32.5 0.693  1.307

Columns: rowid, term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high, am, gear, predicted_lo, predicted_hi, predicted 
Type:  response 
m <- lm(mpg ~ hp + drat + factor(cyl) + factor(am), data = mtcars)
comparisons(m, variables = "hp", newdata = datagrid(FUN_factor = unique, FUN_numeric = median))

 Term Contrast Estimate Std. Error     z Pr(>|z|)   S   2.5 % 97.5 %  hp drat
   hp       +1  -0.0452     0.0149 -3.04  0.00239 8.7 -0.0744 -0.016 123  3.7
   hp       +1  -0.0452     0.0149 -3.04  0.00239 8.7 -0.0744 -0.016 123  3.7
   hp       +1  -0.0452     0.0149 -3.04  0.00239 8.7 -0.0744 -0.016 123  3.7
   hp       +1  -0.0452     0.0149 -3.04  0.00239 8.7 -0.0744 -0.016 123  3.7
   hp       +1  -0.0452     0.0149 -3.04  0.00239 8.7 -0.0744 -0.016 123  3.7
   hp       +1  -0.0452     0.0149 -3.04  0.00239 8.7 -0.0744 -0.016 123  3.7
 cyl am
   6  1
   6  0
   4  1
   4  0
   8  1
   8  0

Columns: rowid, term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high, predicted_lo, predicted_hi, predicted, mpg, hp, drat, cyl, am 
Type:  response 
# Numeric contrasts
mod <- lm(mpg ~ hp, data = mtcars)
avg_comparisons(mod, variables = list(hp = 1))

 Term Contrast Estimate Std. Error     z Pr(>|z|)    S   2.5 %  97.5 %
   hp       +1  -0.0682     0.0101 -6.74   <0.001 35.9 -0.0881 -0.0484

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
avg_comparisons(mod, variables = list(hp = 5))

 Term Contrast Estimate Std. Error     z Pr(>|z|)    S 2.5 % 97.5 %
   hp       +5   -0.341     0.0506 -6.74   <0.001 35.9 -0.44 -0.242

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
avg_comparisons(mod, variables = list(hp = c(90, 100)))

 Term Contrast Estimate Std. Error     z Pr(>|z|)    S  2.5 % 97.5 %
   hp 100 - 90   -0.682      0.101 -6.74   <0.001 35.9 -0.881 -0.484

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
avg_comparisons(mod, variables = list(hp = "iqr"))

 Term Contrast Estimate Std. Error     z Pr(>|z|)    S 2.5 % 97.5 %
   hp  Q3 - Q1     -5.7      0.845 -6.74   <0.001 35.9 -7.35  -4.04

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
avg_comparisons(mod, variables = list(hp = "sd"))

 Term                Contrast Estimate Std. Error     z Pr(>|z|)    S 2.5 %
   hp (x + sd/2) - (x - sd/2)    -4.68      0.694 -6.74   <0.001 35.9 -6.04
 97.5 %
  -3.32

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
avg_comparisons(mod, variables = list(hp = "minmax"))

 Term  Contrast Estimate Std. Error     z Pr(>|z|)    S 2.5 % 97.5 %
   hp Max - Min    -19.3       2.86 -6.74   <0.001 35.9 -24.9  -13.7

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
# 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))

   Term Contrast Estimate Std. Error     z Pr(>|z|)   S 2.5 % 97.5 %
 new_hp   custom    -1.97      0.711 -2.78  0.00547 7.5 -3.37 -0.581

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
# Adjusted Risk Ratio: see the contrasts vignette
mod <- glm(vs ~ mpg, data = mtcars, family = binomial)
avg_comparisons(mod, comparison = "lnratioavg", transform = exp)

 Term Contrast Estimate Pr(>|z|)    S 2.5 % 97.5 %
  mpg mean(+1)     1.13   <0.001 31.9  1.09   1.17

Columns: term, contrast, estimate, p.value, s.value, conf.low, conf.high, predicted_lo, predicted_hi, predicted 
Type:  response 
# Adjusted Risk Ratio: Manual specification of the `comparison`
avg_comparisons(
     mod,
     comparison = function(hi, lo) log(mean(hi) / mean(lo)),
     transform = exp)

 Term Contrast Estimate Pr(>|z|)    S 2.5 % 97.5 %
  mpg       +1     1.13   <0.001 31.9  1.09   1.17

Columns: term, contrast, estimate, p.value, s.value, conf.low, conf.high, predicted_lo, predicted_hi, predicted 
Type:  response 
# cross contrasts
mod <- lm(mpg ~ factor(cyl) * factor(gear) + hp, data = mtcars)
avg_comparisons(mod, variables = c("cyl", "gear"), cross = TRUE)

 Estimate Std. Error      z Pr(>|z|)   S 2.5 % 97.5 % C: cyl C: gear
   -0.631       3.40 -0.185    0.853 0.2 -7.30   6.04  6 - 4   4 - 3
    2.678       4.62  0.580    0.562 0.8 -6.37  11.73  6 - 4   5 - 3
    3.348       6.43  0.521    0.602 0.7 -9.25  15.95  8 - 4   4 - 3
    5.525       5.87  0.942    0.346 1.5 -5.98  17.03  8 - 4   5 - 3

Columns: term, contrast_cyl, contrast_gear, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
# variable-specific contrasts
avg_comparisons(mod, variables = list(gear = "sequential", hp = 10))

 Term Contrast Estimate Std. Error      z Pr(>|z|)   S 2.5 % 97.5 %
 gear    4 - 3    3.409      2.587  1.318   0.1876 2.4 -1.66  8.481
 gear    5 - 4    2.628      2.747  0.957   0.3387 1.6 -2.76  8.011
 hp      +10     -0.574      0.225 -2.552   0.0107 6.5 -1.02 -0.133

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
# 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")

    Term Estimate Std. Error     z Pr(>|z|)    S 2.5 % 97.5 %
 wt=drat    -6.23       1.05 -5.92   <0.001 28.2 -8.29  -4.16

Columns: term, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
# same hypothesis test using row indices
comparisons(
    mod,
    newdata = "mean",
    hypothesis = "b1 - b2 = 0")

    Term Estimate Std. Error    z Pr(>|z|)    S 2.5 % 97.5 %
 b1-b2=0     6.23       1.05 5.92   <0.001 28.2  4.16   8.29

Columns: term, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
# same hypothesis test using numeric vector of weights
comparisons(
    mod,
    newdata = "mean",
    hypothesis = c(1, -1))

   Term Estimate Std. Error    z Pr(>|z|)    S 2.5 % 97.5 %
 custom     6.23       1.05 5.92   <0.001 28.2  4.16   8.29

Columns: term, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
# two custom contrasts using a matrix of weights
lc <- matrix(c(
    1, -1,
    2, 3),
    ncol = 2)
comparisons(
    mod,
    newdata = "mean",
    hypothesis = lc)

   Term Estimate Std. Error     z Pr(>|z|)    S  2.5 % 97.5 %
 custom     6.23       1.05  5.92   <0.001 28.2   4.16   8.29
 custom   -11.46       4.92 -2.33   0.0197  5.7 -21.10  -1.83

Columns: term, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
# Effect of a 1 group-wise standard deviation change
# First we calculate the SD in each group of `cyl`
# Second, we use that SD as the treatment size in the `variables` argument
library(dplyr)
mod <- lm(mpg ~ hp + factor(cyl), mtcars)
tmp <- mtcars %>%
    group_by(cyl) %>%
    mutate(hp_sd = sd(hp))
avg_comparisons(mod, 
    variables = list(hp = function(x) data.frame(x, x + tmp$hp_sd)),
    by = "cyl")

 Term Contrast cyl Estimate Std. Error     z Pr(>|z|)   S 2.5 % 97.5 %
   hp   custom   4   -0.678      0.435 -1.56    0.119 3.1 -1.53  0.174
   hp   custom   6   -1.122      0.719 -1.56    0.119 3.1 -2.53  0.288
   hp   custom   8   -0.818      0.525 -1.56    0.119 3.1 -1.85  0.210

Columns: term, contrast, cyl, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
# `by` argument
mod <- lm(mpg ~ hp * am * vs, data = mtcars)
comparisons(mod, by = TRUE)

 Term Contrast Estimate Std. Error      z Pr(>|z|)    S  2.5 %  97.5 %
   am    1 - 0   4.6980     1.0601  4.432   <0.001 16.7  2.620  6.7758
   hp    +1     -0.0688     0.0182 -3.780   <0.001 12.6 -0.104 -0.0331
   vs    1 - 0  -0.2943     2.3379 -0.126      0.9  0.2 -4.877  4.2879

Columns: term, contrast, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  response 
mod <- lm(mpg ~ hp * am * vs, data = mtcars)
avg_comparisons(mod, variables = "hp", by = c("vs", "am"))

 Term Contrast vs am Estimate Std. Error     z Pr(>|z|)   S   2.5 %   97.5 %
   hp mean(+1)  0  0  -0.0422     0.0248 -1.70  0.08879 3.5 -0.0907  0.00639
   hp mean(+1)  0  1  -0.0368     0.0124 -2.97  0.00297 8.4 -0.0612 -0.01254
   hp mean(+1)  1  0  -0.0994     0.0534 -1.86  0.06289 4.0 -0.2042  0.00534
   hp mean(+1)  1  1  -0.1112     0.0463 -2.40  0.01645 5.9 -0.2020 -0.02034

Columns: term, contrast, vs, am, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high, predicted_lo, predicted_hi, predicted 
Type:  response 
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)

 Term  By  Estimate Std. Error     z Pr(>|z|)   S   2.5 %  97.5 %
  am  3,4 -0.222793    0.07959 -2.80  0.00512 7.6 -0.3788 -0.0668
  mpg 3,4  0.000463    0.00579  0.08  0.93620 0.1 -0.0109  0.0118
  vs  3,4  0.102102    0.07335  1.39  0.16394 2.6 -0.0417  0.2459
  am  5    0.445585    0.15918  2.80  0.00512 7.6  0.1336  0.7576
  mpg 5   -0.000927    0.01158 -0.08  0.93620 0.1 -0.0236  0.0218
  vs  5   -0.204204    0.14671 -1.39  0.16394 2.6 -0.4917  0.0833

Columns: term, by, estimate, std.error, statistic, p.value, s.value, conf.low, conf.high 
Type:  probs