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 = NULL,
hypothesis = NULL,
equivalence = NULL,
df = Inf,
eps = NULL,
...
)

avg_slopes(
model,
newdata = NULL,
variables = NULL,
type = NULL,
by = TRUE,
vcov = TRUE,
conf_level = 0.95,
slope = "dydx",
wts = NULL,
hypothesis = NULL,
equivalence = NULL,
df = Inf,
eps = NULL,
...
)

## Arguments

model

Model object

newdata

Grid of predictor values at which we evaluate the slopes.

• NULL (default): Unit-level slopes for each observed value in the original dataset.

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

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

• See the Examples section and the datagrid() documentation.

• string:

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

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

• "marginalmeans": Marginal Effects at Marginal Means. See Details section below.

• "tukey": Marginal Effects at Tukey's 5 numbers.

• "grid": Marginal Effects on a grid of representative numbers (Tukey's 5 numbers and unique values of categorical predictors).

variables

Focal variables

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

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

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 default value is used. This default is the first model-related row in the marginaleffects:::type_dictionary dataframe.

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.

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

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:

• "dydx": dY/dX

• "eyex": dY/dX * Y / X

• "eydx": dY/dX * Y

• "dyex": dY/dX / X

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.

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

• hp = drat

• hp + drat = 12

• b1 + b2 + b3 = 0

• 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://vincentarelbundock.github.io/marginaleffects/articles/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.

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.

...

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 ?marginaleffects 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.

See ?print.marginaleffects for printing options.

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

## 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://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

## 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

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

## Examples

if (FALSE) { # interactive()
}

# Unit-level (conditional) Marginal Effects
mod <- glm(am ~ hp * wt, data = mtcars, family = binomial)
mfx <- slopes(mod)
#>
#>  Term Estimate Std. Error     z Pr(>|z|)     2.5 %   97.5 %
#>    hp 0.006983   0.005848 1.194    0.232 -0.004478 0.018445
#>    hp 0.016404   0.012338 1.330    0.184 -0.007778 0.040586
#>    hp 0.002828   0.003764 0.751    0.452 -0.004549 0.010206
#>    hp 0.001935   0.002441 0.793    0.428 -0.002848 0.006718
#>    hp 0.002993   0.003203 0.934    0.350 -0.003285 0.009271
#>    hp 0.000148   0.000322 0.458    0.647 -0.000484 0.000779
#>
#> Columns: rowid, term, estimate, std.error, statistic, p.value, conf.low, conf.high, predicted, predicted_hi, predicted_lo, am, hp, wt
#>

# Average Marginal Effect (AME)
avg_slopes(mod, by = TRUE)
#>
#>  Term Estimate Std. Error     z Pr(>|z|)    2.5 %   97.5 %
#>    hp  0.00265    0.00209  1.27  0.20539 -0.00145  0.00676
#>    wt -0.43578    0.14093 -3.09  0.00199 -0.71200 -0.15957
#>
#> Columns: term, estimate, std.error, statistic, p.value, conf.low, conf.high
#>

# Marginal Effect at the Mean (MEM)
slopes(mod, newdata = datagrid())
#>
#>  Term Estimate Std. Error     z Pr(>|z|)    2.5 % 97.5 %  hp   wt
#>    hp  0.00853    0.00823  1.04    0.300 -0.00759 0.0246 147 3.22
#>    wt -1.74453    1.55734 -1.12    0.263 -4.79685 1.3078 147 3.22
#>
#> Columns: rowid, term, estimate, std.error, statistic, p.value, conf.low, conf.high, predicted, predicted_hi, predicted_lo, am, hp, wt
#>

# 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)))
#>
#>  Term Estimate Std. Error      z Pr(>|z|)    2.5 %  97.5 %   wt  hp
#>    hp  0.00117    0.00171  0.684    0.494 -0.00218 0.00451 3.22 100
#>    hp  0.00190    0.00240  0.789    0.430 -0.00281 0.00661 3.22 110
#>    wt -0.19468    0.29925 -0.651    0.515 -0.78119 0.39184 3.22 100
#>    wt -0.33154    0.42925 -0.772    0.440 -1.17284 0.50977 3.22 110
#>
#> Columns: rowid, term, estimate, std.error, statistic, p.value, conf.low, conf.high, predicted, predicted_hi, predicted_lo, am, wt, hp
#>

# 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")
#>
#>  Term    Contrast cyl Estimate Std. Error      z Pr(>|z|)   2.5 %  97.5 %
#>    hp mean(dY/dX)   4  -0.0917     0.0353 -2.596  0.00942 -0.1610 -0.0225
#>    hp mean(dY/dX)   6  -0.0523     0.0204 -2.561  0.01044 -0.0923 -0.0123
#>    hp mean(dY/dX)   8  -0.0128     0.0143 -0.891  0.37280 -0.0409  0.0153
#>
#> Columns: term, contrast, cyl, estimate, std.error, statistic, p.value, conf.low, conf.high, predicted, predicted_hi, predicted_lo
#>

# 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"))
#>
#>  rowidcf Term Estimate Std. Error     z Pr(>|z|)     2.5 %   97.5 %   wt  hp
#>        1   hp 0.012035   0.009939 1.211    0.226 -0.007446 0.031515 2.62 100
#>        2   hp 0.014161   0.010526 1.345    0.179 -0.006470 0.034791 2.88 100
#>        3   hp 0.001564   0.002196 0.712    0.476 -0.002739 0.005868 2.32 100
#>        4   hp 0.001191   0.001733 0.687    0.492 -0.002206 0.004587 3.21 100
#>        5   hp 0.000145   0.000321 0.453    0.651 -0.000484 0.000775 3.44 100
#>        6   hp 0.000120   0.000274 0.439    0.661 -0.000416 0.000657 3.46 100
#>
#> Columns: rowid, rowidcf, term, estimate, std.error, statistic, p.value, conf.low, conf.high, predicted, predicted_hi, predicted_lo, am, wt, hp
#>

# Heteroskedasticity robust standard errors
mfx <- slopes(mod, vcov = sandwich::vcovHC(mod))
#>
#>  Term Estimate Std. Error     z Pr(>|z|)     2.5 %   97.5 %
#>    hp 0.006983   0.009052 0.771    0.440 -0.010759 0.024725
#>    hp 0.016404   0.012458 1.317    0.188 -0.008013 0.040821
#>    hp 0.002828   0.004877 0.580    0.562 -0.006731 0.012388
#>    hp 0.001935   0.002026 0.955    0.340 -0.002036 0.005906
#>    hp 0.002993   0.002907 1.030    0.303 -0.002704 0.008690
#>    hp 0.000148   0.000235 0.628    0.530 -0.000313 0.000609
#>
#> Columns: rowid, term, estimate, std.error, statistic, p.value, conf.low, conf.high, predicted, predicted_hi, predicted_lo, am, hp, wt
#>

# 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")
#>
#>     Term Estimate Std. Error     z Pr(>|z|) 2.5 % 97.5 %
#>  wt=drat    -6.23       1.05 -5.92   <0.001 -8.29  -4.16
#>
#> Columns: term, estimate, std.error, statistic, p.value, conf.low, conf.high
#>

# same hypothesis test using row indices
slopes(
mod,
newdata = "mean",
hypothesis = "b1 - b2 = 0")
#>
#>     Term Estimate Std. Error     z Pr(>|z|) 2.5 % 97.5 %
#>  b1-b2=0    -6.23       1.05 -5.92   <0.001 -8.29  -4.16
#>
#> Columns: term, estimate, std.error, statistic, p.value, conf.low, conf.high
#>

# same hypothesis test using numeric vector of weights
slopes(
mod,
newdata = "mean",
hypothesis = c(1, -1))
#>
#>    Term Estimate Std. Error     z Pr(>|z|) 2.5 % 97.5 %
#>  custom    -6.23       1.05 -5.92   <0.001 -8.29  -4.16
#>
#> Columns: term, estimate, std.error, statistic, p.value, conf.low, conf.high
#>

# 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)
#>
#>        Term Estimate Std. Error      z Pr(>|z|)  2.5 % 97.5 %
#>  Contrast A    -6.23       1.05 -5.919   <0.001  -8.29  -4.16
#>  Contrast B    -5.24       5.62 -0.931    0.352 -16.26   5.78
#>
#> Columns: term, estimate, std.error, statistic, p.value, conf.low, conf.high
#>