% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_emcontrasts.R, R/get_emmeans.R,
%   R/get_emtrends.R, R/get_marginalcontrasts.R, R/get_marginalmeans.R,
%   R/get_marginaltrends.R
\name{get_emcontrasts}
\alias{get_emcontrasts}
\alias{get_emmeans}
\alias{get_emtrends}
\alias{get_marginalcontrasts}
\alias{get_marginalmeans}
\alias{get_marginaltrends}
\title{Consistent API for 'emmeans' and 'marginaleffects'}
\usage{
get_emcontrasts(
  model,
  contrast = NULL,
  by = NULL,
  predict = NULL,
  comparison = "pairwise",
  keep_iterations = FALSE,
  verbose = TRUE,
  ...
)

get_emmeans(
  model,
  by = "auto",
  predict = NULL,
  keep_iterations = FALSE,
  verbose = TRUE,
  ...
)

get_emtrends(
  model,
  trend = NULL,
  by = NULL,
  predict = NULL,
  keep_iterations = FALSE,
  verbose = TRUE,
  ...
)

get_marginalcontrasts(
  model,
  contrast = NULL,
  by = NULL,
  predict = NULL,
  ci = 0.95,
  comparison = "pairwise",
  estimate = NULL,
  transform = NULL,
  post_process = NULL,
  p_adjust = "none",
  keep_iterations = FALSE,
  verbose = TRUE,
  ...
)

get_marginalmeans(
  model,
  by = "auto",
  predict = NULL,
  ci = 0.95,
  estimate = NULL,
  transform = NULL,
  keep_iterations = FALSE,
  verbose = TRUE,
  ...
)

get_marginaltrends(
  model,
  trend = NULL,
  by = NULL,
  predict = NULL,
  ci = 0.95,
  estimate = NULL,
  transform = NULL,
  p_adjust = "none",
  keep_iterations = FALSE,
  verbose = TRUE,
  ...
)
}
\arguments{
\item{model}{A statistical model.}

\item{contrast}{A character vector indicating the name of the variable(s) for
which to compute the contrasts, optionally including representative values or
levels at which contrasts are evaluated (e.g., \code{contrast="x=c('a','b')"}).
\strong{Note:} It is also possible to contrast average slopes, i.e. \code{contrast} can
be the name of two numeric predictors. However, while it is possible to
filter data for one numeric contrast (e.g., \code{contrast = c("num_pred=c(0, 1, 3)")}),
it is not possible to "filter" at certain values for two numeric predictors.
For contrasting slopes, the \code{comparison} will always be \code{"pairwise"}. It is
possible to compute pairwise comparisons of two average slopes at the levels
of a third variable, by also adding that variable to the \code{contrast} argument,
e.g. \code{contrast = c("num1", "num2", "factor")}. See 'Examples'.}

\item{by}{The (focal) predictor variable(s) at which to evaluate the desired
effect / mean / contrasts. Other predictors of the model that are not
included here will be collapsed and "averaged" over (the effect will be
estimated across them). \code{by} can be a character (vector) naming the focal
predictors, optionally including representative values or levels at which
focal predictors are evaluated (e.g., \code{by = "x = c(1, 2)"}). When \code{estimate}
is \emph{not} \code{"average"}, the \code{by} argument is used to create a "reference grid"
or "data grid" with representative values for the focal predictors. In this
case, \code{by} can also be list of named elements. See details in
\code{\link[insight:get_datagrid]{insight::get_datagrid()}} to learn more about how to create data grids for
predictors of interest. For \code{estimate_means()}, \code{by} defaults to \code{"auto"},
which automatically selects the first focal predictor found in the model. If
\code{by = NULL}, the grand mean of the response is predicted.}

\item{predict}{Is passed to the \code{type} argument in \code{emmeans::emmeans()} (when
\code{backend = "emmeans"}) or in \code{marginaleffects::avg_predictions()} (when
\code{backend = "marginaleffects"}). Valid options for \code{predict} are:
\itemize{
\item \code{backend = "marginaleffects"}: \code{predict} can be \code{"response"}, \code{"link"},
\code{"inverse_link"} or any valid \code{type} option supported by model's class
\code{predict()} method (e.g., for zero-inflation models from package
\strong{glmmTMB}, you can choose \code{predict = "zprob"} or \code{predict = "conditional"}
etc., see \link[glmmTMB:predict.glmmTMB]{glmmTMB::predict.glmmTMB}). By default, when \code{predict = NULL},
the most appropriate transformation is selected, which usually returns
predictions or contrasts on the response-scale. The \code{"inverse_link"} is a
special option, comparable to \emph{marginaleffects}' \code{invlink(link)} option. It
will calculate predictions on the link scale and then back-transform to the
response scale.
\item \code{backend = "emmeans"}: \code{predict} can be \code{"response"}, \code{"link"}, \code{"mu"},
\code{"unlink"}, or \code{"log"}. If \code{predict = NULL} (default), the most appropriate
transformation is selected (which usually is \code{"response"}). See also
\href{https://CRAN.R-project.org/package=emmeans/vignettes/transformations.html}{this vignette}.
}

See also section \emph{Predictions on different scales}.}

\item{comparison}{Specify the type of contrasts or tests that should be
carried out. See also section \emph{Comparison options} below for details.
\itemize{
\item When \code{backend = "emmeans"}, can be one of \code{"pairwise"}, \code{"poly"},
\code{"consec"}, \code{"eff"}, \code{"del.eff"}, \code{"mean_chg"}, \code{"trt.vs.ctrl"},
\code{"dunnett"}, \code{"wtcon"} and some more. To test multiple hypotheses jointly
(usually used for factorial designs), \code{comparison} can also be \code{"joint"}.
See also \code{method} argument in \link[emmeans:contrast]{emmeans::contrast} and the
\code{?emmeans::emmc-functions}.
\item For \code{backend = "marginaleffects"}, can be a numeric value, vector, or
matrix, a string equation specifying the hypothesis to test, a string
naming the comparison method, a formula, or a function. For options not
described below, see documentation of \link[marginaleffects:comparisons]{marginaleffects::comparisons},
\href{https://marginaleffects.com/bonus/hypothesis.html}{this website} and
section \emph{Comparison options} below.
\itemize{
\item String: One of \code{"pairwise"}, \code{"revpairwise"}, \code{"reference"},
\code{"sequential"}, \code{"meandev"} \code{"meanotherdev"}, \code{"poly"}, \code{"helmert"}, or
\code{"trt_vs_ctrl"}. To test multiple hypotheses jointly (usually used for
factorial designs), \code{comparison} can also be \code{"joint"} or \code{"omnibus"}. In
this case, use the \code{test} argument to specify which test should be
conducted: \code{"F"} (default) or \code{"Chi2"}, and use argument \code{null} to
specify the null-hypothesis to test against. For \code{"omnibus"}, \code{null} is
set to the overall mean or prevalence/proportion.
\item String: Special string options are \code{"inequality"}, \code{"inequality_ratio"},
and \code{"inequality_pairwise"}. \code{comparison = "inequality"} computes the
marginal effect inequality summary of categorical predictors' overall
effects, respectively, the comprehensive effect of an independent
variable across all outcome categories of a nominal or ordinal dependent
variable (also called \emph{absolute inequality}, or total marginal effect,
see \emph{Mize and Han, 2025}). \code{"inequality_ratio"} computes the ratio of
marginal effect inequality measures, also known as \emph{relative inequality}.
This is useful to compare the relative effects of different predictors on
the dependent variable. It provides a measure of how much more or less
inequality one predictor has compared to another.
\code{comparison = "inequality_pairwise"} computes pairwise differences of
absolute inequality measures, while \code{"inequality_ratio_pairwise"}
computes pairwise differences of relative inequality measures (ratios).
See an overview of applications in the related case study in the
\href{https://easystats.github.io/modelbased/articles/practical_inequalities.html}{vignettes}.
\item String equation: To identify parameters from the output, either specify
the term name, or \code{"b1"}, \code{"b2"} etc. to indicate rows, e.g.:\code{"hp = drat"},
\code{"b1 = b2"}, or \code{"b1 + b2 + b3 = 0"}.
\item Formula: A formula like \verb{<comparison> ~ pairs | group}, where the
left-hand side indicates the type of \verb{<comparison>} (\code{difference} or
\code{ratio}), the right-hand side determines the pairs of estimates to
compare (\code{reference}, \code{pairwise}, \code{sequential}, \code{meandev}, etc., see
string-options). Optionally, comparisons can be carried out within
subsets by indicating the grouping variable after a vertical bar ( \code{|}).
If the left-hand side is missing, it defaults to \code{difference} (i.e.
\code{comparison = ~pairs | group} is identical to
\code{comparison = difference ~ pairs | group}).
\item A custom function, e.g. \code{comparison = I(my_fun(x))}, or
\verb{<comparison> ~ I(my_fun(x)) | groups} (where \verb{<comparison>} can be
\code{difference} or \code{ratio}, or skipped).
\item If contrasts should be calculated (or grouped by) factors, \code{comparison}
can also be a matrix that specifies factor contrasts (see 'Examples').
}
}}

\item{keep_iterations}{If \code{TRUE}, will keep all iterations (draws) of
bootstrapped or Bayesian models. They will be added as additional columns
named \code{iter_1}, \code{iter_2}, and so on. If \code{keep_iterations} is a positive
number, only as many columns as indicated in \code{keep_iterations} will be added
to the output. You can reshape them to a long format by running
\code{\link[bayestestR:reshape_iterations]{bayestestR::reshape_iterations()}}.}

\item{verbose}{Use \code{FALSE} to silence messages and warnings.}

\item{...}{Other arguments passed, for instance, to \code{\link[insight:get_datagrid]{insight::get_datagrid()}},
to functions from the \strong{emmeans} or \strong{marginaleffects} package, or to process
Bayesian models via \code{\link[bayestestR:describe_posterior]{bayestestR::describe_posterior()}}. Examples:
\itemize{
\item \code{insight::get_datagrid()}: Arguments such as \code{length}, \code{digits} or \code{range}
can be used to control the (number of) representative values. For integer
variables, \code{protect_integers} modulates whether these should also be
treated as numerics, i.e. values can have fractions or not.
\item \strong{marginaleffects}: Internally used functions are \code{avg_predictions()} for
means and contrasts, and \code{avg_slope()} for slopes. Therefore, arguments for
instance like \code{vcov}, \code{equivalence}, \code{df}, \code{slope}, \code{hypothesis} or even
\code{newdata} can be passed to those functions. A \code{weights} argument is passed
to the \code{wts} argument in \code{avg_predictions()} or \code{avg_slopes()}, however,
weights can only be applied when \code{estimate} is \code{"average"} or
\code{"population"} (i.e. for those marginalization options that do not use data
grids). Other arguments, such as \code{re.form} or \code{allow.new.levels}, may be
passed to \code{predict()} (which is internally used by \emph{marginaleffects}) if
supported by that model class.
\item \strong{emmeans}: Internally used functions are \code{emmeans()} and \code{emtrends()}.
Additional arguments can be passed to these functions.
\item Bayesian models: For Bayesian models, parameters are cleaned using
\code{bayestestR::describe_posterior()}, thus, arguments like, for example,
\code{centrality}, \code{rope_range}, or \code{test} are passed to that function.
\item Especially for \code{estimate_contrasts()} with integer focal predictors, for
which contrasts should be calculated, use argument \code{integer_as_continuous}
to set the maximum number of unique values in an integer predictor to treat
that predictor as "discrete integer" or as numeric. For the first case,
contrasts are calculated between values of the predictor, for the latter,
contrasts of slopes are calculated. If the integer has more than
\code{integer_as_continuous} unique values, it is treated as numeric. Defaults
to \code{5}. Set to \code{TRUE} to always treat integer predictors as continuous.
\item For count regression models that use an offset term, use \verb{offset = <value>}
to fix the offset at a specific value. Or use \code{estimate = "average"} or
\code{estimate = "population"} without specifying the \code{offset}, to average
predictions over the distribution of the offset (if appropriate).
}}

\item{trend}{A character indicating the name of the variable for which
to compute the slopes. To get marginal effects at specific values, use
\code{trend="<variable>"} along with the \code{by} argument, e.g.
\code{by="<variable> = c(1, 3, 5)"}, or a combination of \code{by} and \code{length}, for
instance, \verb{by="<variable>", length=30}. To calculate average marginal
effects over a range of values, use \code{trend="<variable> = seq(1, 3, 0.1)"} (or
similar) and omit the variable provided in \code{trend} from the \code{by} argument.}

\item{ci}{Confidence Interval (CI) level. Default to \code{0.95} (\verb{95\%}).}

\item{estimate}{The \code{estimate} argument determines how predictions are
averaged ("marginalized") over variables not specified in \code{by} or \code{contrast}
(non-focal predictors). It controls whether predictions represent a "typical"
individual, an "average" individual from the sample, or an "average"
individual from a broader population.
\itemize{
\item \code{"typical"} (Default): Calculates predictions for a balanced data grid
representing all combinations of focal predictor levels (specified in \code{by}).
For non-focal numeric predictors, it uses the mean; for non-focal
categorical predictors, it marginalizes (averages) over the levels. This
represents a "typical" observation based on the data grid and is useful for
comparing groups. It answers: "What would the average outcome be for a
'typical' observation?". This is the default approach when estimating
marginal means using the \emph{emmeans} package.
\item \code{"average"}: Calculates predictions for each observation in the sample and
then averages these predictions within each group defined by the focal
predictors. This reflects the sample's actual distribution of non-focal
predictors, not a balanced grid. It answers: "What is the predicted value
for an average observation in my data?"
\item \code{"population"}: "Clones" each observation, creating copies with all
possible combinations of focal predictor levels. It then averages the
predictions across these "counterfactual" observations (non-observed
permutations) within each group. This extrapolates to a hypothetical
broader population, considering "what if" scenarios. It answers: "What is
the predicted response for the 'average' observation in a broader possible
target population?" This approach mimics a "pseudo-randomization" and hence
can be more apt to generalize, which should be used for \strong{G-computation}
(causal inference, see \emph{Chatton and Rohrer 2024}). \code{"counterfactual"} is an
alias for \code{"population"}.
}

You can set a default option for the \code{estimate} argument via \code{options()},
e.g. \code{options(modelbased_estimate = "average")}.

Note following limitations:
\itemize{
\item When you set \code{estimate} to \code{"average"}, it calculates the average based
only on the data points that actually exist. This is in particular
important for two or more focal predictors, because it doesn't generate a
\emph{complete} grid of all theoretical combinations of predictor values.
Consequently, the output may not include all the values.
\item Filtering the output at values of continuous predictors, e.g.
\code{by = "x=1:5"}, in combination with \code{estimate = "average"} may result in
returning an empty data frame because the requested values may not overlap
with existing data. In such cases, you can use \code{estimate = "typical"} or
use the \code{newdata} argument to provide a data grid of predictor values at
which to evaluate predictions.
\item \code{estimate = "population"} is not available for \code{estimate_slopes()}.
}}

\item{transform}{A function applied to predictions and confidence intervals
to (back-) transform results, which can be useful in case the regression
model has a transformed response variable (e.g., \code{lm(log(y) ~ x)}). For
Bayesian models, this function is applied to individual draws from the
posterior distribution, before computing summaries. Can also be \code{TRUE}, in
which case \code{insight::get_transformation()} is called to determine the
appropriate transformation-function. Note that no standard errors are returned
when transformations are applied.}

\item{post_process}{Optional formula, character string or function (see
\code{comparison}), or a list of formulas, strings or functions, to process
subsequent, multi-step comparisons. After the initial comparison in
\code{comparison} is completed, the results are then post-processed using the
specified post-process tests. See 'Examples'.}

\item{p_adjust}{The p-values adjustment method for frequentist multiple
comparisons. For \code{estimate_slopes()}, multiple comparison only occurs for
Johnson-Neyman intervals, i.e. in case of interactions with two numeric
predictors (one specified in \code{slope}, one in \code{by}). In this case, the
\code{"esarey"} or \code{"sup-t"} options are recommended, but \code{p_adjust} can also be
one of \code{"none"} (default), \code{"hochberg"}, \code{"hommel"}, \code{"bonferroni"}, \code{"BH"},
\code{"BY"}, \code{"fdr"}, \code{"tukey"}, \code{"sidak"}, or \code{"holm"}. \code{"sup-t"} computes
simultaneous confidence bands, also called sup-t confidence band (Montiel
Olea & Plagborg-Møller, 2019).}
}
\description{
These functions are convenient wrappers around the \strong{emmeans} and the
\strong{marginaleffects} packages. They are mostly available for developers who want
to leverage a unified API for getting model-based estimates, and regular users
should use the \verb{estimate_*} set of functions.

The \code{get_emmeans()}, \code{get_emcontrasts()} and \code{get_emtrends()} functions are
wrappers around \code{emmeans::emmeans()} and \code{emmeans::emtrends()}.
}
\examples{
\dontshow{if (insight::check_if_installed("emmeans", quietly = TRUE)) withAutoprint(\{ # examplesIf}
# Basic usage
model <- lm(Sepal.Width ~ Species, data = iris)
get_emcontrasts(model)

\dontrun{
# Dealing with interactions
model <- lm(Sepal.Width ~ Species * Petal.Width, data = iris)
# By default: selects first factor
get_emcontrasts(model)
# Or both
get_emcontrasts(model, contrast = c("Species", "Petal.Width"), length = 2)
# Or with custom specifications
get_emcontrasts(model, contrast = c("Species", "Petal.Width=c(1, 2)"))
# Or modulate it
get_emcontrasts(model, by = "Petal.Width", length = 4)
}
\dontshow{\}) # examplesIf}
\dontshow{if (require("emmeans", quietly = TRUE)) withAutoprint(\{ # examplesIf}
model <- lm(Sepal.Length ~ Species + Petal.Width, data = iris)

# By default, 'by' is set to "Species"
get_emmeans(model)

\dontrun{
# Overall mean (close to 'mean(iris$Sepal.Length)')
get_emmeans(model, by = NULL)

# One can estimate marginal means at several values of a 'modulate' variable
get_emmeans(model, by = "Petal.Width", length = 3)

# Interactions
model <- lm(Sepal.Width ~ Species * Petal.Length, data = iris)

get_emmeans(model)
get_emmeans(model, by = c("Species", "Petal.Length"), length = 2)
get_emmeans(model, by = c("Species", "Petal.Length = c(1, 3, 5)"), length = 2)
}
\dontshow{\}) # examplesIf}
\dontshow{if (insight::check_if_installed("emmeans", quietly = TRUE)) withAutoprint(\{ # examplesIf}
\dontrun{
model <- lm(Sepal.Width ~ Species * Petal.Length, data = iris)

get_emtrends(model)
get_emtrends(model, by = "Species")
get_emtrends(model, by = "Petal.Length")
get_emtrends(model, by = c("Species", "Petal.Length"))
}

model <- lm(Petal.Length ~ poly(Sepal.Width, 4), data = iris)
get_emtrends(model)
get_emtrends(model, by = "Sepal.Width")
\dontshow{\}) # examplesIf}
\dontshow{if (insight::check_if_installed("marginaleffects", quietly = TRUE)) withAutoprint(\{ # examplesIf}
model <- lm(Sepal.Length ~ Species + Petal.Width, data = iris)

# By default, 'by' is set to "Species"
get_marginalmeans(model)

# Overall mean (close to 'mean(iris$Sepal.Length)')
get_marginalmeans(model, by = NULL)

\dontrun{
# One can estimate marginal means at several values of a 'modulate' variable
get_marginalmeans(model, by = "Petal.Width", length = 3)

# Interactions
model <- lm(Sepal.Width ~ Species * Petal.Length, data = iris)

get_marginalmeans(model)
get_marginalmeans(model, by = c("Species", "Petal.Length"), length = 2)
get_marginalmeans(model, by = c("Species", "Petal.Length = c(1, 3, 5)"), length = 2)
}
\dontshow{\}) # examplesIf}
\dontshow{if (insight::check_if_installed("marginaleffects", quietly = TRUE)) withAutoprint(\{ # examplesIf}
model <- lm(Sepal.Width ~ Species * Petal.Length, data = iris)

get_marginaltrends(model, trend = "Petal.Length", by = "Species")
get_marginaltrends(model, trend = "Petal.Length", by = "Petal.Length")
get_marginaltrends(model, trend = "Petal.Length", by = c("Species", "Petal.Length"))
\dontshow{\}) # examplesIf}
}
