This alias is kept for backward compatibility and because some users may prefer that name.

## Usage

```
marginalmeans(
model,
variables = NULL,
newdata = NULL,
vcov = TRUE,
conf_level = 0.95,
type = NULL,
transform = NULL,
cross = FALSE,
hypothesis = NULL,
equivalence = NULL,
p_adjust = NULL,
df = Inf,
wts = "equal",
by = NULL,
...
)
```

## Arguments

- model
Model object

- variables
Focal variables

Character vector of variable names: compute marginal means for each category of the listed variables.

`NULL`

: calculate marginal means for all logical, character, or factor variables in the dataset used to fit`model`

. Hint: Set`cross=TRUE`

to compute marginal means for combinations of focal variables.

- newdata
Grid of predictor values over which we marginalize.

`NULL`

create a grid with all combinations of all categorical predictors in the model. Warning: can be expensive.Character vector: subset of categorical variables to use when building the balanced grid of predictors. Other variables are held to their mean or mode.

Data frame: A data frame which includes all the predictors in the original model. The full dataset is replicated once for every combination of the focal variables in the

`variables`

argument, using the`datagridcf()`

function.

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

- type
string indicates the type (scale) of the predictions used to compute marginal effects or contrasts. 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. If`type`

is`NULL`

and the default value is "response", the function tries to compute marginal means on the link scale before backtransforming them using the inverse link function.- transform
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.

- cross
TRUE or FALSE

`FALSE`

(default): Marginal means are computed for each predictor individually.`TRUE`

: Marginal means are computed for each combination of predictors specified in the`variables`

argument.

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

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

- wts
character value. Weights to use in the averaging.

"equal": each combination of variables in

`newdata`

gets equal weight."cells": each combination of values for the variables in the

`newdata`

gets a weight proportional to its frequency in the original data."proportional": each combination of values for the variables in

`newdata`

-- except for those in the`variables`

argument -- gets a weight proportional to its frequency in the original data.

- by
Collapse marginal means into categories. 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.- ...
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.

## Details

This function begins by calling the `predictions`

function to obtain a
grid of predictors, and adjusted predictions for each cell. The grid
includes all combinations of the categorical variables listed in the
`variables`

and `newdata`

arguments, or all combinations of the
categorical variables used to fit the model if `newdata`

is `NULL`

.
In the prediction grid, numeric variables are held at their means.

After constructing the grid and filling the grid with adjusted predictions,
`marginal_means`

computes marginal means for the variables listed in the
`variables`

argument, by average across all categories in the grid.

`marginal_means`

can only compute standard errors for linear models, or for
predictions on the link scale, that is, with the `type`

argument set to
"link".

The `marginaleffects`

website compares the output of this function to the
popular `emmeans`

package, which provides similar but more advanced
functionality: https://vincentarelbundock.github.io/marginaleffects/

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

```
library(marginaleffects)
# simple marginal means for each level of `cyl`
dat <- mtcars
dat$carb <- factor(dat$carb)
dat$cyl <- factor(dat$cyl)
dat$am <- as.logical(dat$am)
mod <- lm(mpg ~ carb + cyl + am, dat)
marginal_means(
mod,
variables = "cyl")
#>
#> Term Value Mean Std. Error z Pr(>|z|) 2.5 % 97.5 %
#> cyl 6 20.4 1.34 15.2 <0.001 17.8 23.0
#> cyl 4 23.1 1.66 13.9 <0.001 19.9 26.4
#> cyl 8 16.2 1.07 15.1 <0.001 14.1 18.3
#>
#> Results averaged over levels of: carb, am, cyl
#> Columns: term, value, cyl, estimate, std.error, statistic, p.value, conf.low, conf.high
#>
# collapse levels of cyl by averaging
by <- data.frame(
cyl = c(4, 6, 8),
by = c("4 & 6", "4 & 6", "8"))
marginal_means(mod,
variables = "cyl",
by = by)
#>
#> By Mean Std. Error z Pr(>|z|) 2.5 % 97.5 %
#> 4 & 6 21.7 1.13 19.2 <0.001 19.5 24.0
#> 8 16.2 1.07 15.1 <0.001 14.1 18.3
#>
#> Results averaged over levels of: carb, am, cyl
#> Columns: by, estimate, std.error, statistic, p.value, conf.low, conf.high
#>
# pairwise differences between collapsed levels
marginal_means(mod,
variables = "cyl",
by = by,
hypothesis = "pairwise")
#>
#> Term Mean Std. Error z Pr(>|z|) 2.5 % 97.5 %
#> 4 & 6 - 8 5.54 1.51 3.66 <0.001 2.57 8.5
#>
#> Results averaged over levels of: carb, am, cyl
#> Columns: term, estimate, std.error, statistic, p.value, conf.low, conf.high
#>
# cross
marginal_means(mod,
variables = c("cyl", "carb"),
cross = TRUE)
#>
#> Mean Std. Error z Pr(>|z|) 2.5 % 97.5 %
#> 19.1 1.34 14.31 <0.001 16.53 21.8
#> 23.1 1.77 13.08 <0.001 19.63 26.5
#> 22.9 1.87 12.24 <0.001 19.20 26.5
#> 22.6 2.37 9.56 <0.001 17.98 27.2
#> 17.6 3.00 5.85 <0.001 11.68 23.5
#> 17.0 3.48 4.89 <0.001 10.21 23.9
#> 21.9 1.90 11.51 <0.001 18.15 25.6
#> 25.8 1.26 20.43 <0.001 23.34 28.3
#> 25.6 1.17 21.93 <0.001 23.30 27.9
#> 25.3 2.37 10.71 <0.001 20.70 30.0
#> 20.3 3.77 5.39 <0.001 12.91 27.7
#> 19.8 3.81 5.18 <0.001 12.29 27.2
#> 15.0 1.20 12.53 <0.001 12.63 17.3
#> 18.9 1.94 9.74 <0.001 15.11 22.7
#> 18.7 1.57 11.90 <0.001 15.61 21.8
#> 18.4 1.83 10.07 <0.001 14.85 22.0
#> 13.4 3.36 3.99 <0.001 6.81 20.0
#> 12.9 3.00 4.28 <0.001 6.98 18.8
#>
#> Results averaged over levels of: am
#> Columns: cyl, carb, estimate, std.error, statistic, p.value, conf.low, conf.high
#>
# collapsed cross
by <- expand.grid(
cyl = unique(mtcars$cyl),
carb = unique(mtcars$carb))
by$by <- ifelse(
by$cyl == 4,
paste("Control:", by$carb),
paste("Treatment:", by$carb))
# Convert numeric variables to categorical before fitting the model
dat <- mtcars
dat$am <- as.logical(dat$am)
dat$carb <- as.factor(dat$carb)
mod <- lm(mpg ~ hp + am + carb, data = dat)
# Compute and summarize marginal means
marginal_means(mod)
#>
#> Term Value Mean Std. Error z Pr(>|z|) 2.5 % 97.5 %
#> am TRUE 23.1 0.974 23.72 <0.001 21.2 25.0
#> am FALSE 17.9 1.244 14.37 <0.001 15.4 20.3
#> carb 4 18.8 1.042 18.06 <0.001 16.8 20.9
#> carb 1 22.0 1.345 16.35 <0.001 19.4 24.6
#> carb 2 21.5 1.025 20.95 <0.001 19.5 23.5
#> carb 3 20.6 1.780 11.55 <0.001 17.1 24.0
#> carb 6 18.5 3.019 6.12 <0.001 12.6 24.4
#> carb 8 21.6 4.055 5.33 <0.001 13.7 29.6
#>
#> Results averaged over levels of: hp, am, carb
#> Columns: term, value, estimate, std.error, statistic, p.value, conf.low, conf.high
#>
# Contrast between marginal means (carb2 - carb1), or "is the 1st marginal means equal to the 2nd?"
# see the vignette on "Hypothesis Tests and Custom Contrasts" on the `marginaleffects` website.
lc <- c(-1, 1, 0, 0, 0, 0)
marginal_means(mod, variables = "carb", hypothesis = "b2 = b1")
#>
#> Term Mean Std. Error z Pr(>|z|) 2.5 % 97.5 %
#> b2=b1 3.18 1.9 1.67 0.0949 -0.552 6.9
#>
#> Results averaged over levels of: am, carb
#> Columns: term, estimate, std.error, statistic, p.value, conf.low, conf.high
#>
marginal_means(mod, variables = "carb", hypothesis = lc)
#>
#> Term Mean Std. Error z Pr(>|z|) 2.5 % 97.5 %
#> custom 3.18 1.9 1.67 0.0949 -0.552 6.9
#>
#> Results averaged over levels of: am, carb
#> Columns: term, estimate, std.error, statistic, p.value, conf.low, conf.high
#>
# Multiple custom contrasts
lc <- matrix(c(
-2, 1, 1, 0, -1, 1,
-1, 1, 0, 0, 0, 0
),
ncol = 2,
dimnames = list(NULL, c("A", "B")))
marginal_means(mod, variables = "carb", hypothesis = lc)
#>
#> Term Mean Std. Error z Pr(>|z|) 2.5 % 97.5 %
#> A 8.99 4.73 1.90 0.0572 -0.273 18.2
#> B 3.18 1.90 1.67 0.0949 -0.552 6.9
#>
#> Results averaged over levels of: am, carb
#> Columns: term, estimate, std.error, statistic, p.value, conf.low, conf.high
#>
```