diff --git a/DESCRIPTION b/DESCRIPTION index 8b80c64fb..d6a0adda6 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: modelbased Title: Estimation of Model-Based Predictions, Contrasts and Means -Version: 0.18.0.11 +Version: 0.18.0.12 Authors@R: c(person(given = "Dominique", family = "Makowski", diff --git a/R/checks.R b/R/checks.R index 44bfd67f1..1720749af 100644 --- a/R/checks.R +++ b/R/checks.R @@ -1,3 +1,24 @@ +# warn about custom contrasts combined with filtering and `estimate = "average"` +# +# When `estimate = "average"`, predictions are based on the empirical data rather +# than a balanced reference grid. If the user simultaneously filters levels or +# values in `contrast` or `by` (e.g., `contrast = "x = c('a', 'b')"`) and passes +# a custom `comparison` hypothesis using positional row references (such as +# `"b2 - b1"`), the internal row re-ordering can mismatch the filtered rows and +# silently yield wrong contrast estimates. +# +# This helper detects that combination and issues a warning advising the user +# to pass bare variable names to `contrast` and `by` and inspect the row order +# via `estimate_means()` first. +# +# Arguments: +# - estimate: The marginalization type string (e.g., `"average"`). +# - by: Character vector of focal variables (possibly including filter specs). +# - original_contrast: The user-supplied `contrast` argument before cleaning. +# - comparison: The custom hypothesis specification passed to `comparison`. +# +# Returns: `NULL` (called for its warning side-effect). +# #' @keywords internal #' @noRd .check_custom_contrasts_and_filter <- function( @@ -67,6 +88,29 @@ } +# check for missing (all-NA) standard errors ---------------------------------- +# +# In some models - particularly complex mixed-effects models - the underlying +# backend (`{marginaleffects}` or `{emmeans}`) may fail to compute the +# variance-covariance matrix for contrasts, resulting in `SE` values that are +# entirely `NA`. +# +# When `verbose = TRUE` and all standard errors are `NA`, this helper informs +# the user and - if `by` or `contrast` variables are available - constructs a +# ready-to-run two-step workaround using `estimate_relation()` followed by +# `estimate_contrasts()`. +# +# Arguments: +# - out: Formatted data frame of estimated means, contrasts, or slopes. +# - by: Optional character vector of `by` variable names. +# - contrast: Optional character vector of `contrast` variable names. +# - model: The fitted model object (currently unused, kept for consistency). +# - model_name: Deparsed name of the model object for the example code snippet. +# - verbose: Logical, whether to print the informative message. +# - ...: Additional arguments (currently unused). +# +# Returns: `NULL` (called for its message side-effect). +# #' @keywords internal #' @noRd .check_standard_errors <- function( @@ -134,6 +178,32 @@ } +# inform user about how model offset terms are handled ------------------------ +# +# When a regression model includes an `offset()` term and the user has not +# explicitly supplied a fixed `offset` value, passed the offset in `newdata`, or +# included it as a focal predictor in `by`, predictions depend on the chosen +# `estimate` method: +# - `"specific"` / `"typical"` fix the offset at its sample mean. +# - `"average"` / `"population"` average predictions across the empirical +# distribution of the offset. +# +# This helper alerts the user to this behavior and additionally clarifies that +# for log-transformed offsets (e.g., `offset(log(exposure))`), the `offset` +# argument expects values on the original (untransformed) scale. +# +# Arguments: +# - model: The fitted model object. +# - estimate: The marginalization type string (`"specific"`, `"typical"`, +# `"average"`, or `"population"`). +# - offset: The user-supplied `offset` value (if any). +# - my_args: List of parsed focal arguments (containing `$by`). +# - dots: List of additional arguments passed via `...` (checked for `newdata` +# and `offset`). +# - verbose: Logical, whether to display the alert. +# +# Returns: `NULL` (called for its alert side-effect). +# #' @keywords internal #' @noRd .check_offset <- function( @@ -207,6 +277,29 @@ } +# prevent variable names that collide with `{marginaleffects}` output columns - +# +# `{marginaleffects}` reserves specific column names in its returned data frames +# (such as `"rowid"`, `"df"`, `"s.value"`, or `"predicted"`). If a predictor in +# the user's model shares one of these names, `{marginaleffects}` overwrites or +# renames the column, leading to silent miscalculations or downstream failures. +# +# This helper strips filter specifications from focal variables and throws an +# informative error if any predictor name collides with the reserved names for +# the requested estimation type (`"means"` vs. slopes/contrasts). Bayesian +# models are skipped because their output is tidied via `describe_posterior()`. +# +# Arguments: +# - model: The fitted model object. +# - model_info: Model metadata list from `insight::model_info()`. +# - focal: Character vector of all focal predictor names. +# - contrast: Optional character vector of `contrast` predictor names. +# - trend: Optional character vector of `trend` predictor names. +# - type: Estimation context (`"means"` or other, e.g., `"slopes"`), which +# determines the exact set of reserved column names checked. +# +# Returns: `NULL` invisibly (throws an error if a collision is detected). +# #' @keywords internal #' @noRd .check_marginaleffects_names <- function( @@ -268,6 +361,20 @@ } +# harmonize `data` and `newdata` arguments passed via `...` ------------------- +# +# Across the `{easystats}` ecosystem, `data` is supported as a consistent alias +# for `{marginaleffects}`'s `newdata` argument. This helper moves `dots$data` +# into `dots$newdata`, removes `dots$data`, and alerts the user if both were +# supplied simultaneously. +# +# Arguments: +# - dots: Named list of extra arguments captured from `...`. +# - verbose: Logical, whether to alert the user when both `data` and `newdata` +# are present. +# +# Returns: The updated `dots` list with `data` normalized to `newdata`. +# #' @keywords internal #' @noRd .check_dots_data <- function(dots, verbose) { @@ -284,6 +391,24 @@ } +# normalize formula-based inequality comparisons to canonical strings --------- +# +# Users can request inequality / concentration metrics (such as Gini or Atkinson +# indices via `estimate_contrasts()`) either as character keywords (e.g., +# `"inequality"`) or as formulas (e.g., `~inequality` or `ratio ~ inequality`). +# +# This helper converts unstratified inequality formulas into their canonical +# string identifiers so they can be dispatched uniformly, while leaving +# stratified formulas (e.g., `~ inequality | grp1 + grp2`) untouched for later +# processing by `.process_inequality_formula()`. +# +# Arguments: +# - comparison: The `comparison` argument (character string, formula, or +# function). +# +# Returns: A canonical inequality string if `comparison` is an unstratified +# inequality formula; otherwise, the unchanged `comparison` object. +# #' @keywords internal #' @noRd .check_for_inequality_comparison <- function(comparison) { @@ -317,6 +442,17 @@ } +# determine HTML table formatting backend ------------------------------------- +# +# Resolves which table-rendering backend should be used for HTML export methods +# (`print_html()`): `"tt"` when `backend = "tt"` (`{tinytable}`) is explicitly +# requested via `...`, and `"html"` (`{gt}`) otherwise. +# +# Arguments: +# - ...: Additional arguments passed to `print_html()`, checked for `backend`. +# +# Returns: Character string (`"tt"` or `"html"`). +# #' @keywords internal #' @noRd .check_format_backend <- function(...) { @@ -330,6 +466,21 @@ } +# validate the `predict` argument after matching ------------------------------ +# +# Argument validation helpers return `NA` when a user-supplied `predict` string +# does not match any supported prediction scale or type. This helper catches +# that `NA` sentinel and throws a formatted error listing all valid options +# (always including `"response"` and `"link"`). +# +# Arguments: +# - predict: The matched `predict` value (or `NA` if matching failed). +# - valid_types: Character vector of model-specific valid prediction types. +# - error_arg: Name of the argument to display in the error message (usually +# `"predict"`). +# +# Returns: `NULL` (throws an error if `predict` is `NA`). +# #' @keywords internal #' @noRd .check_predict_arg <- function(predict, valid_types, error_arg) { @@ -419,6 +570,19 @@ } +# check that post-filtering results contain at least one row ------------------ +# +# Certain combinations of `by`/`contrast` filters and `estimate = "average"` +# can produce an empty data frame when none of the requested values occur in +# the underlying data. This helper checks for zero-row results and throws a +# standardized error suggesting alternative `estimate` options or `newdata`. +# +# Arguments: +# - result: A data frame of estimated means, contrasts, or slopes. +# - prefix: Optional context-specific sentence prepended to the error message. +# +# Returns: `NULL` (throws an error if `nrow(result) == 0`). +# #' @keywords internal #' @noRd .check_filter_args <- function(result, prefix = "") { @@ -434,6 +598,19 @@ } +# ensure only a single focal predictor is passed to `trend` ------------------- +# +# `estimate_slopes()` computes marginal effects (derivatives) with respect to +# a single numeric focal variable specified in `trend`. If a user passes a +# vector of multiple variables to `trend`, this helper retains only the first +# variable and alerts the user to pass conditioning variables via `by` instead. +# +# Arguments: +# - trend: Character vector specifying the focal trend variable(s). +# - verbose: Logical, whether to display the alert when `length(trend) > 1`. +# +# Returns: A character scalar containing the first element of `trend`. +# #' @param trend The `trend` argument #' @return updated `trend` variable #' @keywords internal @@ -458,3 +635,141 @@ } trend } + + +# Check for valid CI bounds ------------------------------------------------ +# +# When predicting on the response scale (`predict = "response"`), standard errors +# and confidence intervals are typically computed via the delta method directly on +# the response scale. For non-Gaussian models with bounded support (e.g., +# binomial, beta, or count models), this symmetrical approximation can yield +# confidence interval limits outside the theoretically valid parameter space +# (such as negative values or probabilities greater than 1). +# +# By contrast, computing intervals on the link scale and back-transforming them +# (`predict = "inverse_link"`) guarantees bounds within the valid domain, though +# point estimates may require bias adjustment (`bias_correction = TRUE`) due to +# Jensen's inequality. +# +# This helper checks whether any lower or upper confidence limits violate the +# model family's natural boundaries and alerts the user accordingly. +.check_ci_bounds <- function(means, predict, model_info, verbose) { + if (!verbose) { + return() + } + if (!identical(predict, "response")) { + return() + } + + # check which bounds are valid + lower_bound_zero <- any(unlist( + model_info[c("is_binomial", "is_count", "is_negbin", "is_beta")], + use.names = FALSE + )) + upper_bound_one <- any(unlist( + model_info[c("is_binomial", "is_beta")], + use.names = FALSE + )) + + # if lower/upper CI exceeds valid bounds, throw alert + if ( + (lower_bound_zero && any(means$conf.low < 0, na.rm = TRUE)) || + (upper_bound_one && any(means$conf.high > 1, na.rm = TRUE)) + ) { + insight::format_alert( + paste0( + "Some confidence intervals extend beyond plausible bounds. For ", + model_info$family, + " models, `predict = \"response\"` ", + "generally yields less biased point estimates, but symmetric confidence intervals ", + "can fall outside the valid parameter range. Consider using ", + "`predict = \"inverse_link\"` with `bias_correction = TRUE` instead. ", + "Optionally, you can also set `residual_variance` to a sensible value ", + "to specify the assumed variance." + ), + "Set `verbose = FALSE` to silent this message (and other warnings)." + ) + } +} + + +# validate user-specified response categories for ordinal models (emmeans) ---- +# +# When filtering or contrasting specific response levels of a frequentist +# ordinal model (e.g., `by = "Sat = 'Low'"`), the requested values must match +# the outcome categories recognized by the fitted model. This helper extracts +# the model's response levels and throws an error if unknown categories are +# requested. +# +# Arguments: +# - model: The fitted ordinal model object. +# - data: Model data frame (fallback if levels are not stored on `model`). +# - response: Character string naming the ordinal response variable. +# - values: Character vector of requested response category names. +# +# Returns: `NULL` invisibly (throws an error if any `values` are invalid). +# +#' @keywords internal +#' @noRd +.check_ordinal_response_values <- function(model, data, response, values) { + # the categories of the model, which can differ from the factor levels in + # the data (e.g. `clm()` drops unused levels) + response_levels <- model$y.levels + if (is.null(response_levels)) { + response_levels <- model$lev + } + if (is.null(response_levels)) { + response_levels <- levels(droplevels(as.factor(data[[response]]))) + } + unknown <- setdiff(values, response_levels) + if (length(unknown)) { + insight::format_error(paste0( + "The response `", + response, + "` has no ", + if (length(unknown) == 1) "category " else "categories ", + datawizard::text_concatenate(unknown, enclose = "`"), + ". Its categories are ", + datawizard::text_concatenate(response_levels, enclose = "`"), + "." + )) + } + invisible(NULL) +} + + +# restrict ordinal response filtering to `predict = "prob"` (emmeans) --------- +# +# With `backend = "emmeans"`, response categories are only included as a column +# in the output when `predict = "prob"` (the default). Other ordinal modes +# (such as `"cum.prob"`, `"exc.prob"`, `"latent"`, or `"mean.class"`) operate on +# thresholds or latent/mean scales instead. This helper throws an error if the +# user attempts to filter response categories in `by` or `contrast` under any +# mode other than `"prob"`. +# +# Arguments: +# - response_filter: List with elements `$response` and `$values` extracted by +# `.extract_ordinal_response_filter()`, or `NULL`. +# - ordinal_mode: Character string indicating the requested ordinal mode. +# - argument: Name of the argument where filtering was attempted (`"by"` or +# `"contrast"`). +# +# Returns: `NULL` (throws an error if filtering is invalid for `ordinal_mode`). +# +#' @keywords internal +#' @noRd +.check_ordinal_response_filter <- function( + response_filter, + ordinal_mode, + argument = "by" +) { + if (!is.null(response_filter) && !identical(ordinal_mode, "prob")) { + insight::format_error(paste0( + "The response `", + response_filter$response, + "` can only be used in `", + argument, + "` with `predict = \"prob\"` (the default), which returns the probability of each response category." + )) + } +} diff --git a/R/estimate_means.R b/R/estimate_means.R index 541188297..64b54e1cb 100644 --- a/R/estimate_means.R +++ b/R/estimate_means.R @@ -312,18 +312,25 @@ #' can take the value of the parameter you want to estimate, for instance #' `"sigma"`, `"kappa"`, etc. #' -#' `"response"` and `"inverse_link"` both return predictions on the response -#' scale, however, `"response"` first calculates predictions on the response -#' scale for each observation and *then* aggregates them by groups or levels -#' defined in `by`. `"inverse_link"` first calculates predictions on the link -#' scale for each observation, then aggregates them by groups or levels defined -#' in `by`, and finally back-transforms the predictions to the response scale. -#' Both approaches have advantages and disadvantages. `"response"` usually -#' produces less biased predictions, but confidence intervals might be outside -#' reasonable bounds (i.e., for instance can be negative for count data). The -#' `"inverse_link"` approach is more robust in terms of confidence intervals, -#' but might produce biased predictions. However, you can try to set -#' `bias_correction = TRUE`, to adjust for this bias. +#' ## Jensen's Inequality +#' +#' For non-Gaussian models with non-linear link functions, back-transforming +#' aggregated predictions from the link scale does not equal aggregating +#' predictions already transformed to the response scale - a phenomenon known as +#' *Jensen's inequality*. `"response"` and `"inverse_link"` both return +#' predictions on the response scale; however, `"response"` first calculates +#' predictions on the response scale for each observation and *then* aggregates +#' them by the groups or levels defined in `by`. By contrast, `"inverse_link"` +#' first calculates predictions on the link scale for each observation, +#' aggregates them by the groups or levels defined in `by`, and finally +#' back-transforms the predictions to the response scale. Both approaches have +#' advantages and disadvantages. `"response"` usually produces less biased +#' predictions, but confidence intervals may fall outside reasonable bounds (for +#' instance, becoming negative for count data). The `"inverse_link"` approach is +#' more robust in terms of confidence intervals, though it may produce biased +#' predictions. However, you can set `bias_correction = TRUE` to adjust for this +#' bias (and optionally pass a sensible value to `residual_variance` to specify +#' the assumed variance). #' #' In particular for mixed models, using `"response"` is recommended, because #' averaging across random effects groups is then more accurate. diff --git a/R/get_emmeans.R b/R/get_emmeans.R index a2425b71f..87439efad 100644 --- a/R/get_emmeans.R +++ b/R/get_emmeans.R @@ -584,55 +584,6 @@ get_emmeans <- function( } -# stops when `values` are not categories of the ordinal response -.check_ordinal_response_values <- function(model, data, response, values) { - # the categories of the model, which can differ from the factor levels in - # the data (e.g. `clm()` drops unused levels) - response_levels <- model$y.levels - if (is.null(response_levels)) { - response_levels <- model$lev - } - if (is.null(response_levels)) { - response_levels <- levels(droplevels(as.factor(data[[response]]))) - } - unknown <- setdiff(values, response_levels) - if (length(unknown)) { - insight::format_error(paste0( - "The response `", - response, - "` has no ", - if (length(unknown) == 1) "category " else "categories ", - datawizard::text_concatenate(unknown, enclose = "`"), - ". Its categories are ", - datawizard::text_concatenate(response_levels, enclose = "`"), - "." - )) - } - invisible(NULL) -} - - -# the response categories are only in the output for `predict = "prob"`, so -# we cannot use the response in `by` (or `contrast`) for the other modes. -# `ordinal_mode` is the mode the user asked for, not the mode that we use -# internally for slopes -.check_ordinal_response_filter <- function( - response_filter, - ordinal_mode, - argument = "by" -) { - if (!is.null(response_filter) && !identical(ordinal_mode, "prob")) { - insight::format_error(paste0( - "The response `", - response_filter$response, - "` can only be used in `", - argument, - "` with `predict = \"prob\"` (the default), which returns the probability of each response category." - )) - } -} - - # keeps the response categories of `response_contrast_filter` in the emmeans # grid `estimated`, so that only these categories are contrasted. # `pseudo_factor` is the grid column with the response categories diff --git a/R/get_marginalmeans.R b/R/get_marginalmeans.R index 14dda579b..79d805b3b 100644 --- a/R/get_marginalmeans.R +++ b/R/get_marginalmeans.R @@ -262,6 +262,9 @@ get_marginalmeans <- function( means <- .call_marginaleffects(fun_args, post_process, verbose) vcov_means <- .safe(stats::vcov(means)) + # check for valid bounds, when model is glm and predict = "response" + .check_ci_bounds(means, predict_args$predict, model_info, verbose) + # intermediate step: joint tests -------------------------------------------- # --------------------------------------------------------------------------- @@ -347,7 +350,31 @@ get_marginalmeans <- function( # call marginaleffects and process potential errors --------------------------- - +# +# This wrapper function executes `marginaleffects::avg_predictions()` with the +# prepared argument list (`fun_args`) and handles post-processing, error +# translation, and sanity checks. +# +# Specifically, it: +# 1. Calls `marginaleffects::avg_predictions()` inside a `tryCatch()` block, +# suppressing package-level warnings that are handled separately by +# `modelbased`. +# 2. Applies sequential contrast or hypothesis tests via +# `.post_process_comparisons()` if `post_process` is specified (for example, +# when computing contrasts of contrasts / interaction contrasts). +# 3. Intercepts raw errors from `{marginaleffects}` and translates them into +# more user-friendly, context-aware error messages via +# `.check_marginaleffects_errors()`. +# 4. Verifies that the returned data frame is non-empty (e.g., when filtering +# under `estimate = "average"` yields zero matching rows). +# +# Arguments: +# - fun_args: A named list of arguments passed to `marginaleffects::avg_predictions()`. +# - post_process: Optional formula, character string, or list of formulas/strings +# passed to `marginaleffects::hypotheses()` for sequential post-processing. +# - verbose: Logical, whether to display progress alerts during post-processing. +# +# Returns: A `marginaleffects` predictions/comparisons object. .call_marginaleffects <- function(fun_args, post_process = NULL, verbose = TRUE) { out <- tryCatch( { @@ -370,8 +397,28 @@ get_marginalmeans <- function( out } -# process subsequential comparisons --------------------------- +# process sequential comparisons ---------------------------------------------- +# +# This helper applies one or more sequential hypothesis tests (contrasts of +# contrasts, such as difference-in-differences) on top of an existing +# `marginaleffects` output object using `marginaleffects::hypotheses()`. +# +# When `marginaleffects::hypotheses()` is called repeatedly on a previous +# hypothesis object, it replaces readable level names in the `hypothesis` +# column with generic positional indices like `(b1) - (b2)`. This function +# preserves the original parameter and group labels across each step and +# delegates label reconstruction to `.update_post_process_params()`. +# +# Arguments: +# - out: Output object returned by `marginaleffects::avg_predictions()` (or a +# previous `marginaleffects::hypotheses()` call). +# - post_process: A formula, character string, or list thereof specifying the +# sequential hypothesis/contrast tests to apply. +# - verbose: Logical, whether to print an alert for each post-processing step. +# +# Returns: The updated `marginaleffects` object with human-readable `hypothesis` +# labels restored. .post_process_comparisons <- function(out, post_process = NULL, verbose = TRUE) { if (!is.null(post_process)) { # coerce to list @@ -410,6 +457,32 @@ get_marginalmeans <- function( out } + +# update parameter labels after sequential hypothesis tests ------------------- +# +# After `marginaleffects::hypotheses()` computes contrasts of contrasts, its +# `hypothesis` column contains row-index expressions of the form `(b1) - (b2)`. +# This helper maps those row indices (`lhs` and `rhs`) back to the original +# human-readable contrast labels (`temp_params`) and any non-stratified grouping +# variables (`group_params`). +# +# If the post-processing formula includes conditioning/grouping variables +# (e.g., `difference ~ pairwise | group`), those variables are excluded from +# the combined string label because `{marginaleffects}` already retains them +# as dedicated columns in `out`. +# +# Arguments: +# - out: The updated `marginaleffects` object containing `(bX) - (bY)` strings +# in `out$hypothesis`. +# - temp_params: Character vector of parameter/contrast names from the step +# prior to the latest `hypotheses()` call. +# - group_params: Data frame of grouping columns located before the `estimate` +# column in the prior output. +# - post_process: The formula or character string used in the current +# post-processing step. +# +# Returns: A character vector of reconstructed contrast labels (or `NULL` if +# reconstruction fails or `temp_params` is `NULL`). .update_post_process_params <- function( out, temp_params, @@ -481,189 +554,6 @@ get_marginalmeans <- function( } -# create data grid for marginal means ---------------------------------------- -# -# This helper function prepares and creates the data grid (or "reference grid") -# that is used to calculate marginal means. It sets up arguments for and calls -# `insight::get_datagrid()`. It also handles some special cases, like removing -# weights for certain marginalization types, handling offsets, and ensuring -# data types in the grid are consistent with the original model data. -# -# returns: A list containing: -# - `datagrid`: The created data grid. -# - `datagrid_info`: The attributes of the data grid. -# - `dots`: The `...` arguments, with arguments consumed by this function removed. -.get_datagrid_means <- function(model, by, estimate, dots) { - dg_factors <- switch(estimate, specific = "reference", "all") - dg_args <- list( - model, - by = by, - factors = dg_factors, - include_random = TRUE, - verbose = FALSE - ) - # did user request weights? These are not supported for data-grid - # marginalization types - if ( - estimate %in% - c("specific", "typical") && - (!is.null(dots$weights) || !is.null(dots$wts)) - ) { - insight::format_warning( - "Using weights is not possible when `estimate` is set to \"typical\" or \"specific\". Use `estimate = \"average\"` to include weights for marginal means or contrasts." - ) - dots[c("weights", "wts")] <- NULL - } - - # always show all theoretical values by default - if (is.null(dots$preserve_range)) { - dg_args$preserve_range <- FALSE - } - # add user-arguments from "...", but remove those arguments that are already set - dots[c("by", "factors", "include_random", "verbose")] <- NULL - dg_args <- insight::compact_list(c(dg_args, dots)) - - # we first need to determine whether we have an offset term at all - # ========================================================================== - - # for estimate = "population", we need the offset in `by`, thus, we have to - # add it before we call data grid - model_offset <- insight::find_offset(model) - - # offset_arg is a flag for the "offset" argument, which is used by users - # to define a specific offset-value - offset_arg <- (!is.null(dots$offset) && !is.null(model_offset)) - - # check if offset was specified via `offset` argument in the model call, and - # not inside formula. We need to handle this differently. - call_offset <- !is.null(insight::get_call(model)$offset) - - # by_miss_offset is a flag that checks whether the offset-term was - # specified in the "by" argument or not - by_miss_offset <- (!is.null(dg_args$by) && - !is.null(model_offset) && - !any(startsWith(dg_args$by, model_offset))) - - if (offset_arg && estimate == "population" && by_miss_offset) { - dg_args$by <- c(dg_args$by, paste(model_offset, "=", dots$offset)) - } - - # Get corresponding datagrid (and deal with particular ats) - datagrid <- do.call(insight::get_datagrid, dg_args) - datagrid_info <- attributes(datagrid) - - # handle offsets for other estimate-options - if (offset_arg && estimate != "population") { - # if user provided an offset-argument, we use this value in the datagrid - datagrid[[model_offset]] <- dots$offset - } else if (call_offset && estimate != "population") { - # else, we take the mean-value of the offset from the data - model_data <- insight::get_data(model) - datagrid[[model_offset]] <- mean(model_data[[model_offset]], na.rmn = TRUE) - } - - # check if we have a "newdata" argument, where offset is already specified - # if so, we use that data and don't need to do anything else. However, if - # a) model has an offset, b) newdata is provided, and c) model-offset is - # not yet included in the newdata, or explicitly specied in the offset-argument, - # we add/overwrite that value. "datagrid" is already handled above - if ( - !is.null(model_offset) && - !is.null(dots$newdata) && - (!model_offset %in% colnames(dots$newdata) || offset_arg) - ) { - if (offset_arg) { - # use user-specified offset-value - offset_val <- dots$offset - } else { - # take mean from model data - model_data <- insight::get_data(model) - offset_val <- mean(model_data[[model_offset]], na.rmn = TRUE) - } - # add offset-term to newdata - dots$newdata[[model_offset]] <- offset_val - } - - # restore data types - if we have defined numbers in `by`, like - # `by = "predictor = 5"`, and `predictor` was a factor, it is returned as - # numeric in the data grid. Fix this here, else marginal effects will fail - datagrid <- datawizard::data_restoretype( - datagrid, - insight::get_data(model, verbose = FALSE) - ) - - list(datagrid = datagrid, datagrid_info = datagrid_info, dots = dots) -} - - -# filter datagrid for `estimate = "average"`--------------------------------- -# -# This helper function filters the results of marginal means/predictions when -# `estimate = "average"`. For this estimation type, predictions are based on -# the original data, not a theoretical data grid. However, a data grid is -# still created internally to capture user-specified values in the `by` -# argument (e.g., `by = "x = c(1, 2)"`). -# -# This function applies that filtering post-computation. It also performs a -# sanity check to ensure that the values specified for filtering actually -# exist in the data, throwing an informative error if they don't. -# -# Arguments: -# - means: The data frame of marginal means/predictions from {marginaleffects}. -# - estimate: The estimation method string (e.g., "average"). -# - datagrid: The data grid created based on the `by` argument. -# - datagrid_info: Attributes of the data grid, containing focal term info. -# -# returns: The filtered `means` data frame. -.filter_datagrid_average <- function(means, estimate, datagrid, datagrid_info) { - # filter "by" rows when we have "average" marginalization, because we don't - # pass data grid in such situations - but we still created the data grid based - # on the `by` variables, for internal use, for example filtering at this point - if ( - identical(estimate, "average") && - !is.null(datagrid) && - all(datagrid_info$at_specs$varname %in% colnames(means)) - ) { - # sanity check - are all filter values from the data grid in the marginaleffects - # object? For `estimate_average()`, predictions are based on the data, not - # the theoretical data grid. When users request filtering by numeric predictors, - # we need to make sure all filter-values (from which the dummy-data grid is built) - # are available for filter. E.g., `by = "Petal.Width=c(3,5)"` won't work for - # estimate = "average", because 3 and 5 don't appear in the iris data. - filter_ok <- vapply( - datagrid_info$at_specs$varname, - function(j) any(datagrid[[j]] %in% means[[j]]), - logical(1) - ) - # stop if not... - if (!all(filter_ok)) { - # set up for informative error message - invalid_filters <- names(filter_ok)[!filter_ok] - first_invalid <- invalid_filters[1] - example_values <- sample( - unique(means[[first_invalid]]), - pmin(3, insight::n_unique(means[[first_invalid]])) - ) - # tell user... - insight::format_error(paste0( - "None of the values specified for the predictors ", - datawizard::text_concatenate(invalid_filters, enclose = "`"), - " are available in the data. This is required for `estimate=\"average\"`.", - " To resolve this, either select a different option for the `estimate` argument, supply a defined data grid via the `data` argument, or use values that", - " are present in the data, such as ", - datawizard::text_concatenate(example_values, last = " or ", enclose = "`"), - "." - )) - } - # else, filter values - means <- datawizard::data_match(means, datagrid[datagrid_info$at_specs$varname]) - # sanity check - do we have any rows left? - .check_filter_args(means, "No rows left after filtering.") - } - means -} - - # handle attributes ----------------------------------------------------------- # we have following attributes for modelbased-objects: @@ -816,56 +706,3 @@ get_marginalmeans <- function( list(by = by, contrast = contrast) } - - -# create weighted data grid, for faster computation of predictions. Works best -# if reduced data grid is considerably smaller than the original model data, -# and is more efficient if model contains fewer categorical predictors. - -.create_weighted_datagrid <- function(model, estimate, fun_args, dots) { - if ( - !is.null(dots$fast) && - (isTRUE(dots$fast) || is.numeric(dots$fast) || is.na(dots$fast)) - ) { - # this overrides the existing data grid, if any. this means, "fast = TRUE" - # only works with marginal predictions (when `estimate` is "average" or - # "population"), not conditional, datagrid-based predictions (when - # `estimate` is "specific" or "typical") - if (estimate %in% c("specific", "typical")) { - insight::format_error( - "`fast` only works for marginal predictions, i.e. when `estimate` is set to \"average\" or \"population\"." - ) - } - # do we have bins? - n_bins <- dots$n_bins - # if not specified, we default to 5 bins, or to the value provided in "fast" - if (is.null(n_bins)) { - if (is.numeric(dots$fast)) { - # use given number for bins - n_bins <- dots$fast - } else if (is.na(dots$fast)) { - # if "NA", set n_bins to NULL, meaning we just take the mean for - # numerics and only bin categorical predictors - n_bins <- NULL - } else { - # if fast = TRUE, use the default (5 bins for numerics) - n_bins <- 5 - } - } - # does model have weights? - model_weights <- insight::find_weights(model) - # if not, we default to TRUE to trigger weighted data grid. Else, we - # pass the name of the weights variable - if (is.null(model_weights)) { - model_weights <- TRUE - } - # create weighted (reduced) data grid - fast_grid <- insight::get_datagrid(model, n_bins = n_bins, weighted = model_weights) - # update newdata with reduced data grid for faster computation - fun_args$newdata <- fast_grid - dots$weights <- fast_grid$Weight - # clean-up dots - dots$fast <- dots$n_bins <- NULL - } - list(fun_args = fun_args, dots = dots) -} diff --git a/R/utils.R b/R/utils.R index 6053416b8..8e1c74603 100644 --- a/R/utils.R +++ b/R/utils.R @@ -1,3 +1,19 @@ +# list supported distributional / auxiliary parameters for brms models -------- +# +# Distributional regression models (such as `brmsfit` objects) can predict +# auxiliary parameters beyond the location parameter (e.g., `"sigma"`, `"zi"`, +# `"hu"`, `"kappa"`). This helper combines a static set of common distributional +# parameter names with any model-specific auxiliary parameters detected via +# `insight::find_auxiliary()`. +# +# It is used to route `predict = ""` calls to the `dpar` argument in +# `{marginaleffects}` or `{emmeans}` and to recognize valid output column names. +# +# Arguments: +# - model: Optional fitted model object passed to `insight::find_auxiliary()`. +# +# Returns: A character vector of unique auxiliary parameter names. +# #' @keywords internal #' @noRd .brms_aux_elements <- function(model = NULL) { @@ -25,6 +41,24 @@ } +# list valid estimate column names across modelbased outputs ------------------ +# +# Depending on the model family, prediction scale, or estimation function +# (`estimate_means()`, `estimate_contrasts()`, `estimate_slopes()`), the primary +# point-estimate column in the formatted output takes different names (such as +# `"Mean"`, `"Probability"`, `"Difference"`, `"Ratio"`, or `"Slope"`). +# +# This helper returns all recognized coefficient column names, dynamically +# appending title-cased auxiliary parameter names (e.g., `"Sigma"`) if the +# model includes distributional parameters. Used to populate the `"coef_name"` +# attribute for downstream formatting and plotting methods. +# +# Arguments: +# - model: Optional fitted model object used to query distributional +# parameters via `insight::find_auxiliary()`. +# +# Returns: A character vector of valid estimate column names. +# #' @keywords internal #' @noRd .valid_coefficient_names <- function(model = NULL) { @@ -52,7 +86,22 @@ } -# validate estimate argument and handle aliases +# validate `estimate` argument and resolve aliases ---------------------------- +# +# Resolves the marginalization method requested via the `estimate` argument. +# When `estimate = NULL`, it falls back to the global option +# `getOption("modelbased_estimate", "typical")`. It validates the input against +# all supported options and normalizes the alias `"counterfactual"` to its +# canonical name `"population"`. +# +# Arguments: +# - estimate: Character string specifying the marginalization method, or `NULL`. +# +# Returns: A validated character scalar (`"typical"`, `"population"`, +# `"specific"`, or `"average"`). +# +#' @keywords internal +#' @noRd .validate_estimate_arg <- function(estimate) { # set default, if not provided if (is.null(estimate)) { @@ -72,6 +121,21 @@ } +# safely evaluate expressions with optional error fallback -------------------- +# +# Evaluates an R expression inside `tryCatch()`, returning `on_error` (default +# `NULL`) if an error occurs and optionally suppressing warnings. When the +# global debugging option `options(easystats_errors = TRUE)` is active and no +# explicit `on_error` fallback is given, errors are allowed to surface +# unintercepted for easier troubleshooting. +# +# Arguments: +# - code: An R expression to evaluate. +# - on_error: Value returned if `code` throws an error (defaults to `NULL`). +# - quietly: Logical, whether to suppress warnings during evaluation. +# +# Returns: The result of evaluating `code`, or `on_error` upon failure. +# #' @keywords internal #' @noRd .safe <- function(code, on_error = NULL, quietly = FALSE) { @@ -85,6 +149,18 @@ } +# check whether numeric values are whole numbers (integers) ------------------- +# +# Tests element-wise whether values in `x` represent exact integers (including +# whole numbers stored as `double`, such as `c(1, 2, 3)`), returning `FALSE` +# for infinite values or non-numeric types that trigger errors. +# +# Arguments: +# - x: A vector to test. +# +# Returns: A logical vector (or scalar `FALSE` on error) indicating whether each +# element is a finite whole number. +# #' @keywords internal #' @noRd .is_integer <- function(x) { @@ -102,6 +178,31 @@ } +# detect discrete / Likert-style integer predictors --------------------------- +# +# Determines whether a numeric predictor `x` should be treated as a discrete +# integer variable (e.g., an ordinal or Likert-scale item) rather than a +# continuous variable - for example, when deciding between pairwise value +# contrasts and slope contrasts in `estimate_contrasts()`. +# +# A variable is classified as discrete/Likert if all of its values are whole +# numbers (`.is_integer(x)`) and the number of unique values does not exceed +# `integer_as_continuous` (or `getOption("modelbased_integer")`). When a +# variable with 3 to `integer_as_continuous` unique values is auto-detected +# using the default threshold, an informative alert is shown to the user. +# +# Arguments: +# - x: Numeric predictor vector to inspect. +# - integer_as_continuous: Maximum number of unique integer values to treat as +# discrete (default `5`), or `TRUE`/`NA`/`NULL` to disable the check and +# always treat `x` as continuous. +# - verbose: Logical, whether to display an alert when a Likert-scale variable +# is detected using the default threshold. +# - ...: Additional arguments (currently unused). +# +# Returns: Logical scalar (`TRUE` if `x` should be treated as discrete, +# `FALSE` otherwise). +# #' @keywords internal #' @noRd .is_likert <- function(x, integer_as_continuous = 5, verbose = TRUE, ...) { diff --git a/R/utils_datagrid.R b/R/utils_datagrid.R new file mode 100644 index 000000000..f8abdca9d --- /dev/null +++ b/R/utils_datagrid.R @@ -0,0 +1,233 @@ +# create data grid for marginal means ---------------------------------------- +# +# This helper function prepares and creates the data grid (or "reference grid") +# that is used to calculate marginal means. It sets up arguments for and calls +# `insight::get_datagrid()`. It also handles some special cases, like removing +# weights for certain marginalization types, handling offsets, and ensuring +# data types in the grid are consistent with the original model data. +# +# returns: A list containing: +# - `datagrid`: The created data grid. +# - `datagrid_info`: The attributes of the data grid. +# - `dots`: The `...` arguments, with arguments consumed by this function removed. +.get_datagrid_means <- function(model, by, estimate, dots) { + dg_factors <- switch(estimate, specific = "reference", "all") + dg_args <- list( + model, + by = by, + factors = dg_factors, + include_random = TRUE, + verbose = FALSE + ) + # did user request weights? These are not supported for data-grid + # marginalization types + if ( + estimate %in% + c("specific", "typical") && + (!is.null(dots$weights) || !is.null(dots$wts)) + ) { + insight::format_warning( + "Using weights is not possible when `estimate` is set to \"typical\" or \"specific\". Use `estimate = \"average\"` to include weights for marginal means or contrasts." + ) + dots[c("weights", "wts")] <- NULL + } + + # always show all theoretical values by default + if (is.null(dots$preserve_range)) { + dg_args$preserve_range <- FALSE + } + # add user-arguments from "...", but remove those arguments that are already set + dots[c("by", "factors", "include_random", "verbose")] <- NULL + dg_args <- insight::compact_list(c(dg_args, dots)) + + # we first need to determine whether we have an offset term at all + # ========================================================================== + + # for estimate = "population", we need the offset in `by`, thus, we have to + # add it before we call data grid + model_offset <- insight::find_offset(model) + + # offset_arg is a flag for the "offset" argument, which is used by users + # to define a specific offset-value + offset_arg <- (!is.null(dots$offset) && !is.null(model_offset)) + + # check if offset was specified via `offset` argument in the model call, and + # not inside formula. We need to handle this differently. + call_offset <- !is.null(insight::get_call(model)$offset) + + # by_miss_offset is a flag that checks whether the offset-term was + # specified in the "by" argument or not + by_miss_offset <- (!is.null(dg_args$by) && + !is.null(model_offset) && + !any(startsWith(dg_args$by, model_offset))) + + if (offset_arg && estimate == "population" && by_miss_offset) { + dg_args$by <- c(dg_args$by, paste(model_offset, "=", dots$offset)) + } + + # Get corresponding datagrid (and deal with particular ats) + datagrid <- do.call(insight::get_datagrid, dg_args) + datagrid_info <- attributes(datagrid) + + # handle offsets for other estimate-options + if (offset_arg && estimate != "population") { + # if user provided an offset-argument, we use this value in the datagrid + datagrid[[model_offset]] <- dots$offset + } else if (call_offset && estimate != "population") { + # else, we take the mean-value of the offset from the data + model_data <- insight::get_data(model) + datagrid[[model_offset]] <- mean(model_data[[model_offset]], na.rmn = TRUE) + } + + # check if we have a "newdata" argument, where offset is already specified + # if so, we use that data and don't need to do anything else. However, if + # a) model has an offset, b) newdata is provided, and c) model-offset is + # not yet included in the newdata, or explicitly specied in the offset-argument, + # we add/overwrite that value. "datagrid" is already handled above + if ( + !is.null(model_offset) && + !is.null(dots$newdata) && + (!model_offset %in% colnames(dots$newdata) || offset_arg) + ) { + if (offset_arg) { + # use user-specified offset-value + offset_val <- dots$offset + } else { + # take mean from model data + model_data <- insight::get_data(model) + offset_val <- mean(model_data[[model_offset]], na.rmn = TRUE) + } + # add offset-term to newdata + dots$newdata[[model_offset]] <- offset_val + } + + # restore data types - if we have defined numbers in `by`, like + # `by = "predictor = 5"`, and `predictor` was a factor, it is returned as + # numeric in the data grid. Fix this here, else marginal effects will fail + datagrid <- datawizard::data_restoretype( + datagrid, + insight::get_data(model, verbose = FALSE) + ) + + list(datagrid = datagrid, datagrid_info = datagrid_info, dots = dots) +} + + +# filter datagrid for `estimate = "average"`--------------------------------- +# +# This helper function filters the results of marginal means/predictions when +# `estimate = "average"`. For this estimation type, predictions are based on +# the original data, not a theoretical data grid. However, a data grid is +# still created internally to capture user-specified values in the `by` +# argument (e.g., `by = "x = c(1, 2)"`). +# +# This function applies that filtering post-computation. It also performs a +# sanity check to ensure that the values specified for filtering actually +# exist in the data, throwing an informative error if they don't. +# +# Arguments: +# - means: The data frame of marginal means/predictions from {marginaleffects}. +# - estimate: The estimation method string (e.g., "average"). +# - datagrid: The data grid created based on the `by` argument. +# - datagrid_info: Attributes of the data grid, containing focal term info. +# +# returns: The filtered `means` data frame. +.filter_datagrid_average <- function(means, estimate, datagrid, datagrid_info) { + # filter "by" rows when we have "average" marginalization, because we don't + # pass data grid in such situations - but we still created the data grid based + # on the `by` variables, for internal use, for example filtering at this point + if ( + identical(estimate, "average") && + !is.null(datagrid) && + all(datagrid_info$at_specs$varname %in% colnames(means)) + ) { + # sanity check - are all filter values from the data grid in the marginaleffects + # object? For `estimate_average()`, predictions are based on the data, not + # the theoretical data grid. When users request filtering by numeric predictors, + # we need to make sure all filter-values (from which the dummy-data grid is built) + # are available for filter. E.g., `by = "Petal.Width=c(3,5)"` won't work for + # estimate = "average", because 3 and 5 don't appear in the iris data. + filter_ok <- vapply( + datagrid_info$at_specs$varname, + function(j) any(datagrid[[j]] %in% means[[j]]), + logical(1) + ) + # stop if not... + if (!all(filter_ok)) { + # set up for informative error message + invalid_filters <- names(filter_ok)[!filter_ok] + first_invalid <- invalid_filters[1] + example_values <- sample( + unique(means[[first_invalid]]), + pmin(3, insight::n_unique(means[[first_invalid]])) + ) + # tell user... + insight::format_error(paste0( + "None of the values specified for the predictors ", + datawizard::text_concatenate(invalid_filters, enclose = "`"), + " are available in the data. This is required for `estimate=\"average\"`.", + " To resolve this, either select a different option for the `estimate` argument, supply a defined data grid via the `data` argument, or use values that", + " are present in the data, such as ", + datawizard::text_concatenate(example_values, last = " or ", enclose = "`"), + "." + )) + } + # else, filter values + means <- datawizard::data_match(means, datagrid[datagrid_info$at_specs$varname]) + # sanity check - do we have any rows left? + .check_filter_args(means, "No rows left after filtering.") + } + means +} + + +# create weighted data grid, for faster computation of predictions. Works best +# if reduced data grid is considerably smaller than the original model data, +# and is more efficient if model contains fewer categorical predictors. +.create_weighted_datagrid <- function(model, estimate, fun_args, dots) { + if ( + !is.null(dots$fast) && + (isTRUE(dots$fast) || is.numeric(dots$fast) || is.na(dots$fast)) + ) { + # this overrides the existing data grid, if any. this means, "fast = TRUE" + # only works with marginal predictions (when `estimate` is "average" or + # "population"), not conditional, datagrid-based predictions (when + # `estimate` is "specific" or "typical") + if (estimate %in% c("specific", "typical")) { + insight::format_error( + "`fast` only works for marginal predictions, i.e. when `estimate` is set to \"average\" or \"population\"." + ) + } + # do we have bins? + n_bins <- dots$n_bins + # if not specified, we default to 5 bins, or to the value provided in "fast" + if (is.null(n_bins)) { + if (is.numeric(dots$fast)) { + # use given number for bins + n_bins <- dots$fast + } else if (is.na(dots$fast)) { + # if "NA", set n_bins to NULL, meaning we just take the mean for + # numerics and only bin categorical predictors + n_bins <- NULL + } else { + # if fast = TRUE, use the default (5 bins for numerics) + n_bins <- 5 + } + } + # does model have weights? + model_weights <- insight::find_weights(model) + # if not, we default to TRUE to trigger weighted data grid. Else, we + # pass the name of the weights variable + if (is.null(model_weights)) { + model_weights <- TRUE + } + # create weighted (reduced) data grid + fast_grid <- insight::get_datagrid(model, n_bins = n_bins, weighted = model_weights) + # update newdata with reduced data grid for faster computation + fun_args$newdata <- fast_grid + dots$weights <- fast_grid$Weight + # clean-up dots + dots$fast <- dots$n_bins <- NULL + } + list(fun_args = fun_args, dots = dots) +} diff --git a/README.Rmd b/README.Rmd index dcc9fa621..adc36979f 100644 --- a/README.Rmd +++ b/README.Rmd @@ -434,7 +434,7 @@ plot(preds, ribbon = list(alpha = 0)) + # Previous plot The algorithmic heavy lifting is done by `{modelbased}`'s two back-end packages, `{emmeans}` and `{marginaleffects}` (the default), which can be set as a global option (e.g., with `options(modelbased_backend = "emmeans")`). -Of the two, `{emmeans}` [(Russell, 2024)](https://doi.org/10.32614/CRAN.package.emmeans) is the more senior package and was originally known as `{lsmeans}` (for "Least-Squares Means"). This term has been historically used to describe what are now more commonly referred to as "Estimated Marginal Means" or EMMs: predictions made over a regular grid—a grid typically constructed from all possible combinations of the categorical predictors in the model and the mean of numerical predictors. The package was renamed in 2016 to `{emmeans}` to clarify its extension beyond least-squares estimation and its support of a wider range of models (e.g., Bayesian models). +Of the two, `{emmeans}` [(Russell, 2024)](https://doi.org/10.32614/CRAN.package.emmeans) is the more senior package and was originally known as `{lsmeans}` (for "Least-Squares Means"). This term has been historically used to describe what are now more commonly referred to as "Estimated Marginal Means" or EMMs: predictions made over a regular grid - a grid typically constructed from all possible combinations of the categorical predictors in the model and the mean of numerical predictors. The package was renamed in 2016 to `{emmeans}` to clarify its extension beyond least-squares estimation and its support of a wider range of models (e.g., Bayesian models). Within `{emmeans}`, estimates are generated as a linear function of the model's coefficients, with standard errors produced in a similar manner by taking a linear combination of the coefficients' variance-covariance matrix. For example if $b$ is a vector of 4 coefficients, and $V$ is a 4-by-4 matrix of the coefficients' variance-covariance, we can get an estimate and SE for a linear combination (or set of linear combinations) $L$ like so: @@ -457,7 +457,7 @@ These grid predictions are sometimes averaged over (averaging being a linear ope `{marginaleffects}` [(Arel-Bundock et al., 2024)](https://doi.org/10.18637/jss.v111.i09) was more recently introduced and also relies on the Delta method, but uses numeric differentiation (and can easily switch to bootstrap or simulation-based approaches). By default, it estimates various effects by generating two counter-factual predictions of unit-level observations, then taking the difference between them - which can easily be done on the response scale, rather than the link scale. Because these effects are calculated for every observation, they can then be averaged (e.g., as an Average Treatment Effect). This approach is more iterative compared to the linear matrix multiplication used by `{emmeans}`, but is similarly efficient. -While both packages employ the Delta method to obtain standard errors on transformed scales, they differ in how they construct and average predictions. `{emmeans}` often produces *effects at the mean* of non-focal predictors (via linear contrasts), whereas `{marginaleffects}` tends to compute *mean effects* by averaging over observations. Depending on the model and the type of quantity you want to estimate, results from these two approaches can be very similar—or differ in interesting ways. +While both packages employ the Delta method to obtain standard errors on transformed scales, they differ in how they construct and average predictions. `{emmeans}` often produces *effects at the mean* of non-focal predictors (via linear contrasts), whereas `{marginaleffects}` tends to compute *mean effects* by averaging over observations. Depending on the model and the type of quantity you want to estimate, results from these two approaches can be very similar - or differ in interesting ways. Note that `{emmeans}` can also perform numeric differentiation or use non-regular grids, just as `{marginaleffects}` can construct linear predictions at the mean. Because each package has evolved with slightly different philosophies regarding how to form and interpret predictions, users can select whichever approach best suits their research questions. In `{modelbased}`, you can switch easily between either back end by setting the global option, for example `options(modelbased_backend = "marginaleffects")`, to access these features. diff --git a/README.md b/README.md index 76dabe47d..e4e00bf78 100644 --- a/README.md +++ b/README.md @@ -174,14 +174,14 @@ model <- lm(Sepal.Width ~ Species, data = iris) # 2. Obtain estimated means means <- estimate_means(model, by = "Species") means -## Estimated Marginal Means -## +## Conditional Predictions +## ## Species | Mean | SE | 95% CI | t(147) ## ------------------------------------------------ ## setosa | 3.43 | 0.05 | [3.33, 3.52] | 71.36 ## versicolor | 2.77 | 0.05 | [2.68, 2.86] | 57.66 ## virginica | 2.97 | 0.05 | [2.88, 3.07] | 61.91 -## +## ## Variable predicted: Sepal.Width ## Predictors modulated: Species @@ -203,7 +203,7 @@ ggplot(iris, aes(x = Species, y = Sepal.Width)) + theme_minimal() ``` - + You can also get a “quick” plot using the `plot()` function: @@ -211,7 +211,7 @@ You can also get a “quick” plot using the `plot()` function: plot(means) ``` - + ### Contrast analysis @@ -233,20 +233,20 @@ model <- lm(Sepal.Width ~ Species, data = iris) # 2. Estimate marginal contrasts contrasts <- estimate_contrasts(model, contrast = "Species") contrasts -## Marginal Contrasts Analysis -## +## Conditional Contrasts +## ## Level1 | Level2 | Difference | SE | 95% CI | t(147) | p ## ------------------------------------------------------------------------------ ## versicolor | setosa | -0.66 | 0.07 | [-0.79, -0.52] | -9.69 | < .001 ## virginica | setosa | -0.45 | 0.07 | [-0.59, -0.32] | -6.68 | < .001 ## virginica | versicolor | 0.20 | 0.07 | [ 0.07, 0.34] | 3.00 | 0.003 -## +## ## Variable predicted: Sepal.Width ## Predictors contrasted: Species ## p-values are uncorrected. ``` - + ### Check the contrasts at different points of another linear predictor @@ -268,8 +268,8 @@ difference <- estimate_contrasts( ) # no line break for table print(difference, table_width = Inf) -## Marginal Contrasts Analysis -## +## Conditional Contrasts +## ## Level1 | Level2 | Petal.Length | Difference | SE | 95% CI | t(144) | p ## --------------------------------------------------------------------------------------------- ## versicolor | setosa | 1.00 | -1.70 | 0.34 | [-2.37, -1.02] | -4.97 | < .001 @@ -281,7 +281,7 @@ print(difference, table_width = Inf) ## versicolor | setosa | 6.90 | -1.78 | 1.44 | [-4.62, 1.06] | -1.24 | 0.218 ## virginica | setosa | 6.90 | -2.25 | 1.42 | [-5.06, 0.56] | -1.58 | 0.116 ## virginica | versicolor | 6.90 | -0.47 | 0.28 | [-1.03, 0.09] | -1.65 | 0.101 -## +## ## Variable predicted: Sepal.Width ## Predictors contrasted: Species ## p-values are uncorrected. @@ -313,7 +313,7 @@ ggplot(contrasts, aes(x = Petal.Length, y = Difference, )) + theme_modern() ``` - + ### Create smart grids to represent complex interactions @@ -357,7 +357,7 @@ ggplot(iris, aes(x = Petal.Length, y = Sepal.Length)) + theme_minimal() ``` - + ### Generate predictions from your model to compare it with original data @@ -382,8 +382,8 @@ pred1$Petal.Length <- iris$Petal.Length # Add true response # Print first 5 lines of output head(pred1, n = 5) -## Model-based Predictions -## +## Conditional Predictions +## ## Sepal.Length | Predicted | SE | 95% CI | Residuals | Petal.Length ## ------------------------------------------------------------------------- ## 5.10 | 2.38 | 0.10 | [2.19, 2.57] | -0.98 | 1.40 @@ -391,7 +391,7 @@ head(pred1, n = 5) ## 4.70 | 1.63 | 0.12 | [1.39, 1.87] | -0.33 | 1.30 ## 4.60 | 1.45 | 0.13 | [1.19, 1.70] | 0.05 | 1.50 ## 5.00 | 2.19 | 0.10 | [1.99, 2.39] | -0.79 | 1.40 -## +## ## Variable predicted: Petal.Length # Same for model 2 @@ -413,7 +413,7 @@ ggplot(data = pred1, aes(x = Petal.Length, y = Predicted)) + theme_modern() ``` - + ### Extract and format group-level random effects @@ -447,7 +447,7 @@ plot(random) + theme_minimal() ``` - + ### Estimate derivative of non-linear relationships (e.g., in GAMs) @@ -490,7 +490,7 @@ plot(estimate_relation(model, length = 200)) / geom_hline(yintercept = 0, linetype = "dashed") ``` - + ### Describe the smooth term by its linear parts @@ -516,7 +516,7 @@ ggplot(vizdata, aes(x = Petal.Length, y = Predicted)) + theme_modern() ``` - + ``` r @@ -553,7 +553,7 @@ slopes <- estimate_slopes(model, trend = "hp", by = "wt", length = 200) plot(slopes) ``` - + ### Visualize predictions with random effects @@ -577,7 +577,7 @@ preds <- estimate_relation(model, include_random = TRUE) plot(preds, ribbon = list(alpha = 0)) # Make CI ribbon transparent for clarity ``` - + As we can see, each participant has a different “intercept” (starting point on the y-axis), but all their slopes are the same: this is because @@ -593,7 +593,7 @@ preds <- estimate_relation(model, include_random = TRUE) plot(preds, ribbon = list(alpha = 0.1)) ``` - + As we can see, the effect is now different for all participants. Let’s plot, on top of that, the “fixed” effect estimated across all these @@ -607,7 +607,7 @@ plot(preds, ribbon = list(alpha = 0)) + # Previous plot geom_line(data = fixed_pred, aes(x = Days, y = Predicted), linewidth = 2) ``` - + ## Technical Details @@ -621,7 +621,7 @@ Of the two, `{emmeans}` [(Russell, package and was originally known as `{lsmeans}` (for “Least-Squares Means”). This term has been historically used to describe what are now more commonly referred to as “Estimated Marginal Means” or EMMs: -predictions made over a regular grid—a grid typically constructed from +predictions made over a regular grid - a grid typically constructed from all possible combinations of the categorical predictors in the model and the mean of numerical predictors. The package was renamed in 2016 to `{emmeans}` to clarify its extension beyond least-squares estimation and @@ -671,7 +671,7 @@ predictions. `{emmeans}` often produces *effects at the mean* of non-focal predictors (via linear contrasts), whereas `{marginaleffects}` tends to compute *mean effects* by averaging over observations. Depending on the model and the type of quantity you want to estimate, -results from these two approaches can be very similar—or differ in +results from these two approaches can be very similar - or differ in interesting ways. Note that `{emmeans}` can also perform numeric differentiation or use @@ -710,7 +710,7 @@ Conduct](https://easystats.github.io/modelbased/CODE_OF_CONDUCT.html). By contributing to this project, you agree to abide by its terms.
+data-entry-spacing="0" data-line-spacing="2">
diff --git a/man/estimate_contrasts.Rd b/man/estimate_contrasts.Rd index 6d7decbef..74b1ec52d 100644 --- a/man/estimate_contrasts.Rd +++ b/man/estimate_contrasts.Rd @@ -628,23 +628,30 @@ To predict distributional parameters (called "dpar" in other packages), for instance when using complex formulae in \code{brms} models, the \code{predict} argument can take the value of the parameter you want to estimate, for instance \code{"sigma"}, \code{"kappa"}, etc. - -\code{"response"} and \code{"inverse_link"} both return predictions on the response -scale, however, \code{"response"} first calculates predictions on the response -scale for each observation and \emph{then} aggregates them by groups or levels -defined in \code{by}. \code{"inverse_link"} first calculates predictions on the link -scale for each observation, then aggregates them by groups or levels defined -in \code{by}, and finally back-transforms the predictions to the response scale. -Both approaches have advantages and disadvantages. \code{"response"} usually -produces less biased predictions, but confidence intervals might be outside -reasonable bounds (i.e., for instance can be negative for count data). The -\code{"inverse_link"} approach is more robust in terms of confidence intervals, -but might produce biased predictions. However, you can try to set -\code{bias_correction = TRUE}, to adjust for this bias. +\subsection{Jensen's Inequality}{ + +For non-Gaussian models with non-linear link functions, back-transforming +aggregated predictions from the link scale does not equal aggregating +predictions already transformed to the response scale - a phenomenon known as +\emph{Jensen's inequality}. \code{"response"} and \code{"inverse_link"} both return +predictions on the response scale; however, \code{"response"} first calculates +predictions on the response scale for each observation and \emph{then} aggregates +them by the groups or levels defined in \code{by}. By contrast, \code{"inverse_link"} +first calculates predictions on the link scale for each observation, +aggregates them by the groups or levels defined in \code{by}, and finally +back-transforms the predictions to the response scale. Both approaches have +advantages and disadvantages. \code{"response"} usually produces less biased +predictions, but confidence intervals may fall outside reasonable bounds (for +instance, becoming negative for count data). The \code{"inverse_link"} approach is +more robust in terms of confidence intervals, though it may produce biased +predictions. However, you can set \code{bias_correction = TRUE} to adjust for this +bias (and optionally pass a sensible value to \code{residual_variance} to specify +the assumed variance). In particular for mixed models, using \code{"response"} is recommended, because averaging across random effects groups is then more accurate. } +} \examples{ \dontshow{if (all(insight::check_if_installed(c("lme4", "emmeans", "marginaleffects", "parameters", "datawizard", "rstanarm"), quietly = TRUE))) withAutoprint(\{ # examplesIf} diff --git a/man/estimate_means.Rd b/man/estimate_means.Rd index 9ffab4a00..e9c08de09 100644 --- a/man/estimate_means.Rd +++ b/man/estimate_means.Rd @@ -350,23 +350,30 @@ To predict distributional parameters (called "dpar" in other packages), for instance when using complex formulae in \code{brms} models, the \code{predict} argument can take the value of the parameter you want to estimate, for instance \code{"sigma"}, \code{"kappa"}, etc. - -\code{"response"} and \code{"inverse_link"} both return predictions on the response -scale, however, \code{"response"} first calculates predictions on the response -scale for each observation and \emph{then} aggregates them by groups or levels -defined in \code{by}. \code{"inverse_link"} first calculates predictions on the link -scale for each observation, then aggregates them by groups or levels defined -in \code{by}, and finally back-transforms the predictions to the response scale. -Both approaches have advantages and disadvantages. \code{"response"} usually -produces less biased predictions, but confidence intervals might be outside -reasonable bounds (i.e., for instance can be negative for count data). The -\code{"inverse_link"} approach is more robust in terms of confidence intervals, -but might produce biased predictions. However, you can try to set -\code{bias_correction = TRUE}, to adjust for this bias. +\subsection{Jensen's Inequality}{ + +For non-Gaussian models with non-linear link functions, back-transforming +aggregated predictions from the link scale does not equal aggregating +predictions already transformed to the response scale - a phenomenon known as +\emph{Jensen's inequality}. \code{"response"} and \code{"inverse_link"} both return +predictions on the response scale; however, \code{"response"} first calculates +predictions on the response scale for each observation and \emph{then} aggregates +them by the groups or levels defined in \code{by}. By contrast, \code{"inverse_link"} +first calculates predictions on the link scale for each observation, +aggregates them by the groups or levels defined in \code{by}, and finally +back-transforms the predictions to the response scale. Both approaches have +advantages and disadvantages. \code{"response"} usually produces less biased +predictions, but confidence intervals may fall outside reasonable bounds (for +instance, becoming negative for count data). The \code{"inverse_link"} approach is +more robust in terms of confidence intervals, though it may produce biased +predictions. However, you can set \code{bias_correction = TRUE} to adjust for this +bias (and optionally pass a sensible value to \code{residual_variance} to specify +the assumed variance). In particular for mixed models, using \code{"response"} is recommended, because averaging across random effects groups is then more accurate. } +} \section{Finite mixture models}{ diff --git a/man/figures/unnamed-chunk-10-1.png b/man/figures/unnamed-chunk-10-1.png index 9074eee80..3164f2b08 100644 Binary files a/man/figures/unnamed-chunk-10-1.png and b/man/figures/unnamed-chunk-10-1.png differ diff --git a/man/figures/unnamed-chunk-11-1.png b/man/figures/unnamed-chunk-11-1.png index dd262f57e..849e5ee71 100644 Binary files a/man/figures/unnamed-chunk-11-1.png and b/man/figures/unnamed-chunk-11-1.png differ diff --git a/man/figures/unnamed-chunk-12-1.png b/man/figures/unnamed-chunk-12-1.png index c6ee7e84b..0f7d4291c 100644 Binary files a/man/figures/unnamed-chunk-12-1.png and b/man/figures/unnamed-chunk-12-1.png differ diff --git a/man/figures/unnamed-chunk-13-1.png b/man/figures/unnamed-chunk-13-1.png index 47fd090a2..a54c66a66 100644 Binary files a/man/figures/unnamed-chunk-13-1.png and b/man/figures/unnamed-chunk-13-1.png differ diff --git a/man/figures/unnamed-chunk-14-1.png b/man/figures/unnamed-chunk-14-1.png index 7dd1f0b27..91d849cbe 100644 Binary files a/man/figures/unnamed-chunk-14-1.png and b/man/figures/unnamed-chunk-14-1.png differ diff --git a/man/figures/unnamed-chunk-15-1.png b/man/figures/unnamed-chunk-15-1.png index 02bb9f946..fa0908a7e 100644 Binary files a/man/figures/unnamed-chunk-15-1.png and b/man/figures/unnamed-chunk-15-1.png differ diff --git a/man/figures/unnamed-chunk-16-1.png b/man/figures/unnamed-chunk-16-1.png index 2fce4ab64..8ca162259 100644 Binary files a/man/figures/unnamed-chunk-16-1.png and b/man/figures/unnamed-chunk-16-1.png differ diff --git a/man/figures/unnamed-chunk-17-1.png b/man/figures/unnamed-chunk-17-1.png index 60d45fc97..9b88b9b98 100644 Binary files a/man/figures/unnamed-chunk-17-1.png and b/man/figures/unnamed-chunk-17-1.png differ diff --git a/man/figures/unnamed-chunk-3-1.png b/man/figures/unnamed-chunk-3-1.png index 85de25911..3a2dc958f 100644 Binary files a/man/figures/unnamed-chunk-3-1.png and b/man/figures/unnamed-chunk-3-1.png differ diff --git a/man/figures/unnamed-chunk-4-1.png b/man/figures/unnamed-chunk-4-1.png index 1dd93dc62..e0c9452fb 100644 Binary files a/man/figures/unnamed-chunk-4-1.png and b/man/figures/unnamed-chunk-4-1.png differ diff --git a/man/figures/unnamed-chunk-6-1.png b/man/figures/unnamed-chunk-6-1.png index 9fa1e2a61..5ba12bc16 100644 Binary files a/man/figures/unnamed-chunk-6-1.png and b/man/figures/unnamed-chunk-6-1.png differ diff --git a/man/figures/unnamed-chunk-8-1.png b/man/figures/unnamed-chunk-8-1.png index 1eaa0f804..e9df43d76 100644 Binary files a/man/figures/unnamed-chunk-8-1.png and b/man/figures/unnamed-chunk-8-1.png differ diff --git a/man/figures/unnamed-chunk-9-1.png b/man/figures/unnamed-chunk-9-1.png index 72c8f3605..b67c81921 100644 Binary files a/man/figures/unnamed-chunk-9-1.png and b/man/figures/unnamed-chunk-9-1.png differ diff --git a/tests/testthat/_snaps/estimate_means_mixed.md b/tests/testthat/_snaps/estimate_means_mixed.md index e431b10df..9ccd7cf80 100644 --- a/tests/testthat/_snaps/estimate_means_mixed.md +++ b/tests/testthat/_snaps/estimate_means_mixed.md @@ -31,6 +31,14 @@ Code estimate_means(m, c("mined", "spp"), backend = "marginaleffects") + Message + Some confidence intervals extend beyond plausible bounds. For poisson + models, `predict = "response"` generally yields less biased point + estimates, but symmetric confidence intervals can fall outside the valid + parameter range. Consider using `predict = "inverse_link"` with + `bias_correction = TRUE` instead. Optionally, you can also set + `residual_variance` to a sensible value to specify the assumed variance. + Set `verbose = FALSE` to silent this message (and other warnings). Output Conditional Predictions diff --git a/tests/testthat/_snaps/linux/estimate_contrasts.md b/tests/testthat/_snaps/linux/estimate_contrasts.md new file mode 100644 index 000000000..de0d98ac4 --- /dev/null +++ b/tests/testthat/_snaps/linux/estimate_contrasts.md @@ -0,0 +1,679 @@ +# estimate_contrasts - Frequentist, duplicated levels + + Code + print(estimate_contrasts(model, contrast = c("three", "vs", "am"), backend = "marginaleffects"), + digits = 1, zap_small = TRUE, table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(24) | p + ---------------------------------------------------------------------------------------------- + three 0, vs 0, am 1 | three 0, vs 0, am 0 | 2.9 | 2.2 | [ -1.8, 7.5] | 1.3 | 0.213 + three 0, vs 1, am 0 | three 0, vs 0, am 0 | 5.8 | 2.5 | [ 0.8, 10.9] | 2.4 | 0.026 + three 0, vs 1, am 1 | three 0, vs 0, am 0 | 14.0 | 2.1 | [ 9.7, 18.4] | 6.7 | < .001 + three 1, vs 0, am 0 | three 0, vs 0, am 0 | -0.6 | 2.0 | [ -4.7, 3.6] | -0.3 | 0.780 + three 1, vs 0, am 1 | three 0, vs 0, am 0 | 7.5 | 2.8 | [ 1.7, 13.4] | 2.7 | 0.014 + three 1, vs 1, am 0 | three 0, vs 0, am 0 | 5.1 | 2.2 | [ 0.5, 9.7] | 2.3 | 0.032 + three 1, vs 1, am 1 | three 0, vs 0, am 0 | 10.6 | 2.8 | [ 4.7, 16.4] | 3.7 | 0.001 + three 0, vs 1, am 0 | three 0, vs 0, am 1 | 3.0 | 2.7 | [ -2.5, 8.4] | 1.1 | 0.275 + three 0, vs 1, am 1 | three 0, vs 0, am 1 | 11.2 | 2.3 | [ 6.4, 16.0] | 4.8 | < .001 + three 1, vs 0, am 0 | three 0, vs 0, am 1 | -3.4 | 2.2 | [ -8.1, 1.2] | -1.5 | 0.139 + three 1, vs 0, am 1 | three 0, vs 0, am 1 | 4.7 | 3.0 | [ -1.6, 10.9] | 1.5 | 0.135 + three 1, vs 1, am 0 | three 0, vs 0, am 1 | 2.2 | 2.5 | [ -2.8, 7.3] | 0.9 | 0.374 + three 1, vs 1, am 1 | three 0, vs 0, am 1 | 7.7 | 3.0 | [ 1.5, 13.9] | 2.6 | 0.017 + three 0, vs 1, am 1 | three 0, vs 1, am 0 | 8.2 | 2.5 | [ 3.0, 13.4] | 3.2 | 0.004 + three 1, vs 0, am 0 | three 0, vs 1, am 0 | -6.4 | 2.5 | [-11.5, -1.3] | -2.6 | 0.016 + three 1, vs 0, am 1 | three 0, vs 1, am 0 | 1.7 | 3.2 | [ -4.9, 8.2] | 0.5 | 0.600 + three 1, vs 1, am 0 | three 0, vs 1, am 0 | -0.7 | 2.7 | [ -6.2, 4.7] | -0.3 | 0.782 + three 1, vs 1, am 1 | three 0, vs 1, am 0 | 4.7 | 3.2 | [ -1.8, 11.3] | 1.5 | 0.149 + three 1, vs 0, am 0 | three 0, vs 1, am 1 | -14.6 | 2.1 | [-18.9, -10.3] | -6.9 | < .001 + three 1, vs 0, am 1 | three 0, vs 1, am 1 | -6.5 | 2.9 | [-12.5, -0.5] | -2.2 | 0.035 + three 1, vs 1, am 0 | three 0, vs 1, am 1 | -8.9 | 2.3 | [-13.7, -4.1] | -3.8 | < .001 + three 1, vs 1, am 1 | three 0, vs 1, am 1 | -3.5 | 2.9 | [ -9.5, 2.5] | -1.2 | 0.246 + three 1, vs 0, am 1 | three 1, vs 0, am 0 | 8.1 | 2.8 | [ 2.2, 13.9] | 2.8 | 0.009 + three 1, vs 1, am 0 | three 1, vs 0, am 0 | 5.7 | 2.2 | [ 1.0, 10.3] | 2.5 | 0.019 + three 1, vs 1, am 1 | three 1, vs 0, am 0 | 11.1 | 2.8 | [ 5.3, 17.0] | 3.9 | < .001 + three 1, vs 1, am 0 | three 1, vs 0, am 1 | -2.4 | 3.0 | [ -8.6, 3.8] | -0.8 | 0.428 + three 1, vs 1, am 1 | three 1, vs 0, am 1 | 3.1 | 3.5 | [ -4.1, 10.2] | 0.9 | 0.389 + three 1, vs 1, am 1 | three 1, vs 1, am 0 | 5.5 | 3.0 | [ -0.7, 11.7] | 1.8 | 0.081 + + Variable predicted: mpg + Predictors contrasted: three, vs, am + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model, contrast = "am", backend = "marginaleffects"), + zap_small = TRUE, table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(24) | p + ------------------------------------------------------------------- + 1 | 0 | 6.15 | 1.34 | [3.40, 8.91] | 4.61 | < .001 + + Variable predicted: mpg + Predictors contrasted: am + Predictors averaged over a balanced grid: three, vs + p-values are uncorrected. + +# estimate_contrasts - filtering works + + Code + print(estimate_contrasts(fit, "c172code", backend = "marginaleffects"), + table_width = Inf, zap_small = TRUE) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(827) | p + -------------------------------------------------------------------- + mid | low | -0.09 | 0.34 | [-0.76, 0.58] | -0.25 | 0.802 + high | low | 0.61 | 0.43 | [-0.24, 1.45] | 1.40 | 0.162 + high | mid | 0.69 | 0.36 | [-0.02, 1.40] | 1.92 | 0.055 + + Variable predicted: neg_c_7 + Predictors contrasted: c172code + Predictors averaged over a balanced grid: e16sex, c161sex + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(fit, "c161sex", "c172code", backend = "marginaleffects"), + table_width = Inf, zap_small = TRUE) + Output + Conditional Contrasts + + Level1 | Level2 | c172code | Difference | SE | 95% CI | t(825) | p + ------------------------------------------------------------------------------- + Female | Male | low | 1.05 | 0.69 | [-0.31, 2.40] | 1.51 | 0.131 + Female | Male | mid | 0.56 | 0.42 | [-0.26, 1.38] | 1.35 | 0.178 + Female | Male | high | 0.96 | 0.69 | [-0.39, 2.30] | 1.40 | 0.163 + + Variable predicted: neg_c_7 + Predictors contrasted: c161sex + Predictors averaged over a balanced grid: e16sex + p-values are uncorrected. + +--- + + Code + print(estimate_slopes(fit, "barthtot", backend = "marginaleffects"), + table_width = Inf, zap_small = TRUE) + Output + Estimated Marginal Effects + + Slope | SE | 95% CI | t(810) | p + ----------------------------------------------- + -0.05 | 0.00 | [-0.06, -0.05] | -12.77 | < .001 + + Marginal effects estimated for barthtot + Type of slope was dY/dX + +--- + + Code + print(estimate_slopes(fit, "barthtot", by = "c172code", backend = "marginaleffects"), + table_width = Inf, zap_small = TRUE) + Output + Estimated Marginal Effects + + c172code | Slope | SE | 95% CI | t(808) | p + ---------------------------------------------------------- + low | -0.06 | 0.01 | [-0.08, -0.05] | -7.08 | < .001 + mid | -0.05 | 0.01 | [-0.06, -0.04] | -9.82 | < .001 + high | -0.05 | 0.01 | [-0.07, -0.03] | -4.53 | < .001 + + Marginal effects estimated for barthtot + Type of slope was dY/dX + +--- + + Code + print(estimate_contrasts(fit, "barthtot", "c172code", backend = "marginaleffects"), + table_width = Inf, zap_small = TRUE) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(808) | p + -------------------------------------------------------------------- + mid | low | 0.01 | 0.01 | [-0.01, 0.03] | 1.17 | 0.243 + high | low | 0.02 | 0.01 | [-0.01, 0.04] | 1.10 | 0.270 + high | mid | 0.00 | 0.01 | [-0.02, 0.03] | 0.27 | 0.786 + + Variable predicted: neg_c_7 + Predictors contrasted: barthtot + Predictors held at: barthtot (65) + Predictors averaged over a balanced grid: e16sex + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(fit, "barthtot", c("c172code", "e16sex"), backend = "marginaleffects"), + table_width = Inf, zap_small = TRUE) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(803) | p + ------------------------------------------------------------------------------- + low, female | low, male | -0.01 | 0.02 | [-0.04, 0.03] | -0.35 | 0.729 + mid, male | low, male | -0.01 | 0.02 | [-0.04, 0.02] | -0.46 | 0.648 + mid, female | low, male | 0.02 | 0.01 | [-0.01, 0.05] | 1.24 | 0.217 + high, male | low, male | 0.00 | 0.02 | [-0.05, 0.04] | -0.16 | 0.876 + high, female | low, male | 0.02 | 0.02 | [-0.01, 0.06] | 1.19 | 0.236 + mid, male | low, female | 0.00 | 0.02 | [-0.03, 0.03] | -0.08 | 0.940 + mid, female | low, female | 0.02 | 0.01 | [ 0.00, 0.05] | 1.76 | 0.079 + high, male | low, female | 0.00 | 0.02 | [-0.04, 0.05] | 0.12 | 0.908 + high, female | low, female | 0.03 | 0.02 | [-0.01, 0.06] | 1.58 | 0.115 + mid, female | mid, male | 0.03 | 0.01 | [ 0.00, 0.05] | 2.23 | 0.026 + high, male | mid, male | 0.00 | 0.02 | [-0.04, 0.05] | 0.18 | 0.859 + high, female | mid, male | 0.03 | 0.02 | [ 0.00, 0.06] | 1.83 | 0.068 + high, male | mid, female | -0.02 | 0.02 | [-0.06, 0.02] | -1.08 | 0.280 + high, female | mid, female | 0.00 | 0.01 | [-0.02, 0.03] | 0.26 | 0.792 + high, female | high, male | 0.03 | 0.02 | [-0.02, 0.07] | 1.11 | 0.269 + + Variable predicted: neg_c_7 + Predictors contrasted: barthtot + Predictors held at: barthtot (65) + p-values are uncorrected. + +# estimate_contrasts - simple contrasts and with - in levels works + + Code + print(estimate_contrasts(model, "Species", backend = "marginaleffects"), + table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(146) | p + ---------------------------------------------------------------------------- + versicolor | setosa | 1.46 | 0.11 | [1.24, 1.68] | 13.01 | < .001 + virginica | setosa | 1.95 | 0.10 | [1.75, 2.14] | 19.47 | < .001 + virginica | versicolor | 0.49 | 0.09 | [0.31, 0.67] | 5.41 | < .001 + + Variable predicted: Sepal.Length + Predictors contrasted: Species + Predictors held at: Sepal.Width (3.1) + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(m, c("time", "coffee"), backend = "marginaleffects"), + zap_small = TRUE, table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(113) | p + --------------------------------------------------------------------------------------------- + morning, control | morning, coffee | -5.78 | 1.99 | [-9.73, -1.83] | -2.90 | 0.004 + noon, coffee | morning, coffee | -1.93 | 1.99 | [-5.88, 2.02] | -0.97 | 0.336 + noon, control | morning, coffee | 0.00 | 1.99 | [-3.95, 3.95] | 0.00 | > .999 + afternoon, coffee | morning, coffee | 1.93 | 1.99 | [-2.02, 5.88] | 0.97 | 0.336 + afternoon, control | morning, coffee | 0.00 | 1.99 | [-3.95, 3.95] | 0.00 | > .999 + noon, coffee | morning, control | 3.86 | 1.99 | [-0.09, 7.81] | 1.93 | 0.056 + noon, control | morning, control | 5.78 | 1.99 | [ 1.83, 9.73] | 2.90 | 0.004 + afternoon, coffee | morning, control | 7.71 | 1.99 | [ 3.76, 11.66] | 3.87 | < .001 + afternoon, control | morning, control | 5.78 | 1.99 | [ 1.83, 9.73] | 2.90 | 0.004 + noon, control | noon, coffee | 1.93 | 1.99 | [-2.02, 5.88] | 0.97 | 0.336 + afternoon, coffee | noon, coffee | 3.86 | 1.99 | [-0.09, 7.81] | 1.93 | 0.056 + afternoon, control | noon, coffee | 1.93 | 1.99 | [-2.02, 5.88] | 0.97 | 0.336 + afternoon, coffee | noon, control | 1.93 | 1.99 | [-2.02, 5.88] | 0.97 | 0.336 + afternoon, control | noon, control | 0.00 | 1.99 | [-3.95, 3.95] | 0.00 | > .999 + afternoon, control | afternoon, coffee | -1.93 | 1.99 | [-5.88, 2.02] | -0.97 | 0.336 + + Variable predicted: alertness + Predictors contrasted: time, coffee + Predictors averaged over a balanced grid: sex + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(m, contrast = "time", by = "coffee", backend = "marginaleffects"), + zap_small = TRUE, table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | coffee | Difference | SE | 95% CI | t(113) | p + ----------------------------------------------------------------------------------- + noon | morning | coffee | -1.93 | 1.99 | [-5.88, 2.02] | -0.97 | 0.336 + afternoon | morning | coffee | 1.93 | 1.99 | [-2.02, 5.88] | 0.97 | 0.336 + afternoon | noon | coffee | 3.86 | 1.99 | [-0.09, 7.81] | 1.93 | 0.056 + noon | morning | control | 5.78 | 1.99 | [ 1.83, 9.73] | 2.90 | 0.004 + afternoon | morning | control | 5.78 | 1.99 | [ 1.83, 9.73] | 2.90 | 0.004 + afternoon | noon | control | 0.00 | 1.99 | [-3.95, 3.95] | 0.00 | > .999 + + Variable predicted: alertness + Predictors contrasted: time + Predictors averaged over a balanced grid: sex + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model, contrast = c("mined", "spp"), backend = "marginaleffects"), + zap_small = TRUE, table_width = Inf) + Message + Some confidence intervals extend beyond plausible bounds. For poisson + models, `predict = "response"` generally yields less biased point + estimates, but symmetric confidence intervals can fall outside the valid + parameter range. Consider using `predict = "inverse_link"` with + `bias_correction = TRUE` instead. Optionally, you can also set + `residual_variance` to a sensible value to specify the assumed variance. + Set `verbose = FALSE` to silent this message (and other warnings). + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | z | p + ----------------------------------------------------------------------------- + yes, PR | yes, GP | 0.06 | 0.05 | [-0.04, 0.16] | 1.10 | 0.271 + yes, DM | yes, GP | 0.32 | 0.11 | [ 0.10, 0.54] | 2.89 | 0.004 + yes, EC-A | yes, GP | 0.04 | 0.05 | [-0.05, 0.13] | 0.80 | 0.421 + yes, EC-L | yes, GP | 0.17 | 0.08 | [ 0.02, 0.32] | 2.19 | 0.028 + yes, DES-L | yes, GP | 0.43 | 0.14 | [ 0.17, 0.70] | 3.19 | 0.001 + yes, DF | yes, GP | 0.43 | 0.14 | [ 0.17, 0.70] | 3.19 | 0.001 + no, GP | yes, GP | 2.59 | 0.55 | [ 1.50, 3.67] | 4.67 | < .001 + no, PR | yes, GP | 0.51 | 0.16 | [ 0.20, 0.82] | 3.21 | 0.001 + no, DM | yes, GP | 2.86 | 0.61 | [ 1.68, 4.05] | 4.73 | < .001 + no, EC-A | yes, GP | 1.10 | 0.27 | [ 0.57, 1.64] | 4.03 | < .001 + no, EC-L | yes, GP | 4.67 | 0.94 | [ 2.82, 6.52] | 4.95 | < .001 + no, DES-L | yes, GP | 4.62 | 0.93 | [ 2.79, 6.45] | 4.95 | < .001 + no, DF | yes, GP | 2.24 | 0.49 | [ 1.28, 3.20] | 4.58 | < .001 + yes, DM | yes, PR | 0.26 | 0.11 | [ 0.05, 0.48] | 2.43 | 0.015 + yes, EC-A | yes, PR | -0.02 | 0.06 | [-0.13, 0.09] | -0.33 | 0.740 + yes, EC-L | yes, PR | 0.11 | 0.08 | [-0.04, 0.27] | 1.43 | 0.154 + yes, DES-L | yes, PR | 0.38 | 0.13 | [ 0.12, 0.64] | 2.86 | 0.004 + yes, DF | yes, PR | 0.38 | 0.13 | [ 0.12, 0.64] | 2.86 | 0.004 + no, GP | yes, PR | 2.53 | 0.56 | [ 1.44, 3.62] | 4.54 | < .001 + no, PR | yes, PR | 0.45 | 0.16 | [ 0.13, 0.77] | 2.75 | 0.006 + no, DM | yes, PR | 2.80 | 0.61 | [ 1.61, 4.00] | 4.61 | < .001 + no, EC-A | yes, PR | 1.05 | 0.28 | [ 0.50, 1.59] | 3.76 | < .001 + no, EC-L | yes, PR | 4.61 | 0.95 | [ 2.76, 6.47] | 4.87 | < .001 + no, DES-L | yes, PR | 4.56 | 0.94 | [ 2.73, 6.40] | 4.87 | < .001 + no, DF | yes, PR | 2.18 | 0.49 | [ 1.22, 3.15] | 4.44 | < .001 + yes, EC-A | yes, DM | -0.28 | 0.11 | [-0.50, -0.07] | -2.59 | 0.010 + yes, EC-L | yes, DM | -0.15 | 0.11 | [-0.36, 0.06] | -1.39 | 0.164 + yes, DES-L | yes, DM | 0.11 | 0.13 | [-0.14, 0.36] | 0.89 | 0.375 + yes, DF | yes, DM | 0.11 | 0.13 | [-0.14, 0.36] | 0.89 | 0.375 + no, GP | yes, DM | 2.27 | 0.58 | [ 1.14, 3.40] | 3.93 | < .001 + no, PR | yes, DM | 0.19 | 0.20 | [-0.21, 0.58] | 0.93 | 0.352 + no, DM | yes, DM | 2.54 | 0.63 | [ 1.31, 3.77] | 4.04 | < .001 + no, EC-A | yes, DM | 0.78 | 0.31 | [ 0.18, 1.38] | 2.56 | 0.011 + no, EC-L | yes, DM | 4.35 | 0.96 | [ 2.46, 6.24] | 4.51 | < .001 + no, DES-L | yes, DM | 4.30 | 0.95 | [ 2.43, 6.17] | 4.51 | < .001 + no, DF | yes, DM | 1.92 | 0.51 | [ 0.91, 2.93] | 3.74 | < .001 + yes, EC-L | yes, EC-A | 0.13 | 0.08 | [-0.02, 0.29] | 1.68 | 0.093 + yes, DES-L | yes, EC-A | 0.40 | 0.13 | [ 0.14, 0.66] | 2.97 | 0.003 + yes, DF | yes, EC-A | 0.40 | 0.13 | [ 0.14, 0.66] | 2.97 | 0.003 + no, GP | yes, EC-A | 2.55 | 0.56 | [ 1.46, 3.64] | 4.58 | < .001 + no, PR | yes, EC-A | 0.47 | 0.16 | [ 0.15, 0.79] | 2.90 | 0.004 + no, DM | yes, EC-A | 2.82 | 0.61 | [ 1.63, 4.01] | 4.65 | < .001 + no, EC-A | yes, EC-A | 1.06 | 0.28 | [ 0.52, 1.61] | 3.85 | < .001 + no, EC-L | yes, EC-A | 4.63 | 0.95 | [ 2.78, 6.48] | 4.90 | < .001 + no, DES-L | yes, EC-A | 4.58 | 0.94 | [ 2.75, 6.42] | 4.90 | < .001 + no, DF | yes, EC-A | 2.20 | 0.49 | [ 1.24, 3.17] | 4.49 | < .001 + yes, DES-L | yes, EC-L | 0.26 | 0.13 | [ 0.02, 0.51] | 2.08 | 0.037 + yes, DF | yes, EC-L | 0.26 | 0.13 | [ 0.02, 0.51] | 2.08 | 0.037 + no, GP | yes, EC-L | 2.42 | 0.57 | [ 1.31, 3.53] | 4.28 | < .001 + no, PR | yes, EC-L | 0.34 | 0.18 | [-0.01, 0.69] | 1.89 | 0.058 + no, DM | yes, EC-L | 2.69 | 0.62 | [ 1.48, 3.90] | 4.37 | < .001 + no, EC-A | yes, EC-L | 0.93 | 0.29 | [ 0.37, 1.50] | 3.23 | 0.001 + no, EC-L | yes, EC-L | 4.50 | 0.95 | [ 2.63, 6.37] | 4.72 | < .001 + no, DES-L | yes, EC-L | 4.45 | 0.94 | [ 2.60, 6.30] | 4.71 | < .001 + no, DF | yes, EC-L | 2.07 | 0.50 | [ 1.09, 3.05] | 4.14 | < .001 + yes, DF | yes, DES-L | 0.00 | 0.13 | [-0.26, 0.26] | 0.00 | > .999 + no, GP | yes, DES-L | 2.15 | 0.59 | [ 1.00, 3.31] | 3.67 | < .001 + no, PR | yes, DES-L | 0.07 | 0.22 | [-0.36, 0.50] | 0.33 | 0.738 + no, DM | yes, DES-L | 2.43 | 0.64 | [ 1.18, 3.68] | 3.81 | < .001 + no, EC-A | yes, DES-L | 0.67 | 0.32 | [ 0.04, 1.29] | 2.09 | 0.037 + no, EC-L | yes, DES-L | 4.24 | 0.97 | [ 2.33, 6.14] | 4.36 | < .001 + no, DES-L | yes, DES-L | 4.19 | 0.96 | [ 2.30, 6.07] | 4.35 | < .001 + no, DF | yes, DES-L | 1.81 | 0.52 | [ 0.78, 2.83] | 3.45 | < .001 + no, GP | yes, DF | 2.15 | 0.59 | [ 1.00, 3.31] | 3.67 | < .001 + no, PR | yes, DF | 0.07 | 0.22 | [-0.36, 0.50] | 0.33 | 0.738 + no, DM | yes, DF | 2.43 | 0.64 | [ 1.18, 3.68] | 3.81 | < .001 + no, EC-A | yes, DF | 0.67 | 0.32 | [ 0.04, 1.29] | 2.09 | 0.037 + no, EC-L | yes, DF | 4.24 | 0.97 | [ 2.33, 6.14] | 4.36 | < .001 + no, DES-L | yes, DF | 4.19 | 0.96 | [ 2.30, 6.07] | 4.35 | < .001 + no, DF | yes, DF | 1.81 | 0.52 | [ 0.78, 2.83] | 3.45 | < .001 + no, PR | no, GP | -2.08 | 0.48 | [-3.02, -1.14] | -4.35 | < .001 + no, DM | no, GP | 0.27 | 0.37 | [-0.46, 1.00] | 0.73 | 0.466 + no, EC-A | no, GP | -1.49 | 0.41 | [-2.29, -0.68] | -3.61 | < .001 + no, EC-L | no, GP | 2.08 | 0.58 | [ 0.95, 3.21] | 3.61 | < .001 + no, DES-L | no, GP | 2.03 | 0.57 | [ 0.92, 3.15] | 3.57 | < .001 + no, DF | no, GP | -0.35 | 0.35 | [-1.04, 0.35] | -0.98 | 0.328 + no, DM | no, PR | 2.35 | 0.53 | [ 1.32, 3.39] | 4.47 | < .001 + no, EC-A | no, PR | 0.59 | 0.23 | [ 0.14, 1.05] | 2.56 | 0.011 + no, EC-L | no, PR | 4.16 | 0.86 | [ 2.49, 5.84] | 4.87 | < .001 + no, DES-L | no, PR | 4.11 | 0.85 | [ 2.45, 5.77] | 4.86 | < .001 + no, DF | no, PR | 1.73 | 0.42 | [ 0.92, 2.55] | 4.15 | < .001 + no, EC-A | no, DM | -1.76 | 0.46 | [-2.65, -0.87] | -3.86 | < .001 + no, EC-L | no, DM | 1.81 | 0.55 | [ 0.73, 2.89] | 3.29 | < .001 + no, DES-L | no, DM | 1.76 | 0.54 | [ 0.70, 2.82] | 3.24 | 0.001 + no, DF | no, DM | -0.62 | 0.38 | [-1.36, 0.12] | -1.65 | 0.100 + no, EC-L | no, EC-A | 3.57 | 0.77 | [ 2.07, 5.07] | 4.66 | < .001 + no, DES-L | no, EC-A | 3.52 | 0.76 | [ 2.03, 5.00] | 4.65 | < .001 + no, DF | no, EC-A | 1.14 | 0.36 | [ 0.43, 1.85] | 3.16 | 0.002 + no, DES-L | no, EC-L | -0.05 | 0.48 | [-0.99, 0.89] | -0.10 | 0.918 + no, DF | no, EC-L | -2.43 | 0.61 | [-3.63, -1.22] | -3.95 | < .001 + no, DF | no, DES-L | -2.38 | 0.61 | [-3.57, -1.19] | -3.92 | < .001 + + Variable predicted: count + Predictors contrasted: mined, spp + Predictors held at: cover (8.7e-11) + Random effects: Averaged over a balanced grid of cluster levels. + p-values are uncorrected. + Contrasts are on the response-scale. + +--- + + Code + print(estimate_contrasts(model, contrast = "mined", by = "spp", backend = "marginaleffects"), + zap_small = TRUE, table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | spp | Difference | SE | 95% CI | z | p + -------------------------------------------------------------------------- + no | yes | GP | 2.59 | 0.55 | [1.50, 3.67] | 4.67 | < .001 + no | yes | PR | 0.45 | 0.16 | [0.13, 0.77] | 2.75 | 0.006 + no | yes | DM | 2.54 | 0.63 | [1.31, 3.77] | 4.04 | < .001 + no | yes | EC-A | 1.06 | 0.28 | [0.52, 1.61] | 3.85 | < .001 + no | yes | EC-L | 4.50 | 0.95 | [2.63, 6.37] | 4.72 | < .001 + no | yes | DES-L | 4.19 | 0.96 | [2.30, 6.07] | 4.35 | < .001 + no | yes | DF | 1.81 | 0.52 | [0.78, 2.83] | 3.45 | < .001 + + Variable predicted: count + Predictors contrasted: mined + Predictors held at: cover (8.7e-11) + Random effects: Averaged over a balanced grid of cluster levels. + p-values are uncorrected. + Contrasts are on the response-scale. + +# estimate_contrasts - examples from docs work as intendec + + Code + print(estimate_contrasts(model, contrast = c("Species", "Petal.Width"), length = 2), + zap_small = TRUE, table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(144) | p + ---------------------------------------------------------------------------------------- + setosa, 2.5 | setosa, 0.1 | 2.01 | 0.98 | [ 0.08, 3.94] | 2.06 | 0.041 + versicolor, 0.1 | setosa, 0.1 | -1.83 | 0.28 | [-2.38, -1.28] | -6.55 | < .001 + versicolor, 2.5 | setosa, 0.1 | 0.70 | 0.27 | [ 0.17, 1.23] | 2.61 | 0.010 + virginica, 0.1 | setosa, 0.1 | -1.55 | 0.31 | [-2.17, -0.93] | -4.95 | < .001 + virginica, 2.5 | setosa, 0.1 | -0.03 | 0.11 | [-0.25, 0.19] | -0.29 | 0.773 + versicolor, 0.1 | setosa, 2.5 | -3.84 | 0.96 | [-5.73, -1.95] | -4.01 | < .001 + versicolor, 2.5 | setosa, 2.5 | -1.31 | 0.95 | [-3.19, 0.58] | -1.37 | 0.172 + virginica, 0.1 | setosa, 2.5 | -3.56 | 0.97 | [-5.47, -1.65] | -3.68 | < .001 + virginica, 2.5 | setosa, 2.5 | -2.04 | 0.92 | [-3.86, -0.22] | -2.21 | 0.028 + versicolor, 2.5 | versicolor, 0.1 | 2.53 | 0.52 | [ 1.50, 3.56] | 4.86 | < .001 + virginica, 0.1 | versicolor, 0.1 | 0.28 | 0.41 | [-0.52, 1.08] | 0.69 | 0.492 + virginica, 2.5 | versicolor, 0.1 | 1.80 | 0.28 | [ 1.24, 2.35] | 6.35 | < .001 + virginica, 0.1 | versicolor, 2.5 | -2.25 | 0.40 | [-3.04, -1.46] | -5.64 | < .001 + virginica, 2.5 | versicolor, 2.5 | -0.73 | 0.27 | [-1.27, -0.20] | -2.70 | 0.008 + virginica, 2.5 | virginica, 0.1 | 1.52 | 0.37 | [ 0.77, 2.26] | 4.04 | < .001 + + Variable predicted: Sepal.Width + Predictors contrasted: Species, Petal.Width + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model, contrast = c("Species", "Petal.Width=c(1, 2)")), + zap_small = TRUE, table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(144) | p + ------------------------------------------------------------------------------------ + setosa, 2 | setosa, 1 | 0.84 | 0.41 | [ 0.03, 1.64] | 2.06 | 0.041 + versicolor, 1 | setosa, 1 | -1.63 | 0.32 | [-2.27, -1.00] | -5.09 | < .001 + versicolor, 2 | setosa, 1 | -0.58 | 0.35 | [-1.26, 0.10] | -1.68 | 0.096 + virginica, 1 | setosa, 1 | -1.73 | 0.35 | [-2.43, -1.04] | -4.93 | < .001 + virginica, 2 | setosa, 1 | -1.10 | 0.31 | [-1.72, -0.48] | -3.52 | < .001 + versicolor, 1 | setosa, 2 | -2.47 | 0.72 | [-3.89, -1.05] | -3.43 | < .001 + versicolor, 2 | setosa, 2 | -1.42 | 0.73 | [-2.86, 0.03] | -1.94 | 0.055 + virginica, 1 | setosa, 2 | -2.57 | 0.73 | [-4.02, -1.12] | -3.50 | < .001 + virginica, 2 | setosa, 2 | -1.94 | 0.72 | [-3.35, -0.52] | -2.71 | 0.008 + versicolor, 2 | versicolor, 1 | 1.05 | 0.22 | [ 0.62, 1.48] | 4.86 | < .001 + virginica, 1 | versicolor, 1 | -0.10 | 0.19 | [-0.47, 0.27] | -0.54 | 0.589 + virginica, 2 | versicolor, 1 | 0.53 | 0.09 | [ 0.35, 0.71] | 5.72 | < .001 + virginica, 1 | versicolor, 2 | -1.15 | 0.23 | [-1.60, -0.71] | -5.13 | < .001 + virginica, 2 | versicolor, 2 | -0.52 | 0.16 | [-0.84, -0.21] | -3.31 | 0.001 + virginica, 2 | virginica, 1 | 0.63 | 0.16 | [ 0.32, 0.94] | 4.04 | < .001 + + Variable predicted: Sepal.Width + Predictors contrasted: Species, Petal.Width=c(1, 2) + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model, by = "Petal.Width", length = 4), zap_small = TRUE, + table_width = Inf) + Message + We selected `contrast=c("Species")`. + Output + Conditional Contrasts + + Level1 | Level2 | Petal.Width | Difference | SE | 95% CI | t(144) | p + -------------------------------------------------------------------------------------------- + versicolor | setosa | 0.10 | -1.83 | 0.28 | [-2.38, -1.28] | -6.55 | < .001 + virginica | setosa | 0.10 | -1.55 | 0.31 | [-2.17, -0.93] | -4.95 | < .001 + virginica | versicolor | 0.10 | 0.28 | 0.41 | [-0.52, 1.08] | 0.69 | 0.492 + versicolor | setosa | 0.90 | -1.65 | 0.29 | [-2.22, -1.08] | -5.74 | < .001 + virginica | setosa | 0.90 | -1.71 | 0.32 | [-2.35, -1.07] | -5.28 | < .001 + virginica | versicolor | 0.90 | -0.06 | 0.21 | [-0.47, 0.35] | -0.28 | 0.780 + versicolor | setosa | 1.70 | -1.48 | 0.60 | [-2.67, -0.29] | -2.47 | 0.015 + virginica | setosa | 1.70 | -1.88 | 0.60 | [-3.06, -0.70] | -3.14 | 0.002 + virginica | versicolor | 1.70 | -0.40 | 0.11 | [-0.62, -0.17] | -3.50 | < .001 + versicolor | setosa | 2.50 | -1.31 | 0.95 | [-3.19, 0.58] | -1.37 | 0.172 + virginica | setosa | 2.50 | -2.04 | 0.92 | [-3.86, -0.22] | -2.21 | 0.028 + virginica | versicolor | 2.50 | -0.73 | 0.27 | [-1.27, -0.20] | -2.70 | 0.008 + + Variable predicted: Sepal.Width + Predictors contrasted: Species + p-values are uncorrected. + +# estimate_contrasts - test all combinations of contrast and by, with filtering + + Code + print(estimate_contrasts(model2, c("grp", "time", "x")), zap_small = TRUE, + table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(992) | p + -------------------------------------------------------------------------------------- + control, 1, b | control, 1, a | 0.15 | 0.13 | [-0.10, 0.40] | 1.20 | 0.231 + control, 2, a | control, 1, a | 0.03 | 0.13 | [-0.23, 0.28] | 0.19 | 0.847 + control, 2, b | control, 1, a | 0.09 | 0.13 | [-0.16, 0.34] | 0.73 | 0.465 + treatment, 1, a | control, 1, a | 0.19 | 0.13 | [-0.06, 0.45] | 1.49 | 0.137 + treatment, 1, b | control, 1, a | -0.03 | 0.13 | [-0.28, 0.22] | -0.22 | 0.824 + treatment, 2, a | control, 1, a | 0.02 | 0.13 | [-0.23, 0.27] | 0.19 | 0.850 + treatment, 2, b | control, 1, a | 0.05 | 0.12 | [-0.19, 0.28] | 0.37 | 0.712 + control, 2, a | control, 1, b | -0.12 | 0.13 | [-0.38, 0.13] | -0.97 | 0.332 + control, 2, b | control, 1, b | -0.06 | 0.12 | [-0.30, 0.19] | -0.46 | 0.648 + treatment, 1, a | control, 1, b | 0.04 | 0.13 | [-0.20, 0.29] | 0.34 | 0.730 + treatment, 1, b | control, 1, b | -0.18 | 0.12 | [-0.42, 0.06] | -1.45 | 0.147 + treatment, 2, a | control, 1, b | -0.13 | 0.12 | [-0.37, 0.12] | -1.02 | 0.307 + treatment, 2, b | control, 1, b | -0.10 | 0.12 | [-0.34, 0.13] | -0.89 | 0.376 + control, 2, b | control, 2, a | 0.07 | 0.13 | [-0.19, 0.32] | 0.52 | 0.604 + treatment, 1, a | control, 2, a | 0.17 | 0.13 | [-0.09, 0.43] | 1.26 | 0.207 + treatment, 1, b | control, 2, a | -0.05 | 0.13 | [-0.31, 0.20] | -0.41 | 0.680 + treatment, 2, a | control, 2, a | 0.00 | 0.13 | [-0.26, 0.25] | -0.01 | 0.991 + treatment, 2, b | control, 2, a | 0.02 | 0.13 | [-0.23, 0.27] | 0.16 | 0.876 + treatment, 1, a | control, 2, b | 0.10 | 0.13 | [-0.15, 0.35] | 0.78 | 0.437 + treatment, 1, b | control, 2, b | -0.12 | 0.13 | [-0.37, 0.12] | -0.97 | 0.333 + treatment, 2, a | control, 2, b | -0.07 | 0.13 | [-0.32, 0.18] | -0.55 | 0.582 + treatment, 2, b | control, 2, b | -0.05 | 0.12 | [-0.29, 0.19] | -0.40 | 0.691 + treatment, 1, b | treatment, 1, a | -0.22 | 0.13 | [-0.47, 0.03] | -1.73 | 0.083 + treatment, 2, a | treatment, 1, a | -0.17 | 0.13 | [-0.42, 0.08] | -1.32 | 0.187 + treatment, 2, b | treatment, 1, a | -0.15 | 0.12 | [-0.39, 0.09] | -1.20 | 0.230 + treatment, 2, a | treatment, 1, b | 0.05 | 0.12 | [-0.19, 0.30] | 0.42 | 0.676 + treatment, 2, b | treatment, 1, b | 0.07 | 0.12 | [-0.16, 0.31] | 0.61 | 0.541 + treatment, 2, b | treatment, 2, a | 0.02 | 0.12 | [-0.21, 0.26] | 0.18 | 0.861 + + Variable predicted: score + Predictors contrasted: grp, time, x + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model2, c("grp", "time"), by = "x"), zap_small = TRUE, + table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | x | Difference | SE | 95% CI | t(992) | p + ------------------------------------------------------------------------------------ + control, 2 | control, 1 | a | 0.03 | 0.13 | [-0.23, 0.28] | 0.19 | 0.847 + treatment, 1 | control, 1 | a | 0.19 | 0.13 | [-0.06, 0.45] | 1.49 | 0.137 + treatment, 2 | control, 1 | a | 0.02 | 0.13 | [-0.23, 0.27] | 0.19 | 0.850 + treatment, 1 | control, 2 | a | 0.17 | 0.13 | [-0.09, 0.43] | 1.26 | 0.207 + treatment, 2 | control, 2 | a | 0.00 | 0.13 | [-0.26, 0.25] | -0.01 | 0.991 + treatment, 2 | treatment, 1 | a | -0.17 | 0.13 | [-0.42, 0.08] | -1.32 | 0.187 + control, 2 | control, 1 | b | -0.06 | 0.12 | [-0.30, 0.19] | -0.46 | 0.648 + treatment, 1 | control, 1 | b | -0.18 | 0.12 | [-0.42, 0.06] | -1.45 | 0.147 + treatment, 2 | control, 1 | b | -0.10 | 0.12 | [-0.34, 0.13] | -0.89 | 0.376 + treatment, 1 | control, 2 | b | -0.12 | 0.13 | [-0.37, 0.12] | -0.97 | 0.333 + treatment, 2 | control, 2 | b | -0.05 | 0.12 | [-0.29, 0.19] | -0.40 | 0.691 + treatment, 2 | treatment, 1 | b | 0.07 | 0.12 | [-0.16, 0.31] | 0.61 | 0.541 + + Variable predicted: score + Predictors contrasted: grp, time + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model2, "grp", by = c("time", "x")), zap_small = TRUE, + table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | time | x | Difference | SE | 95% CI | t(992) | p + ----------------------------------------------------------------------------------- + treatment | control | 1 | a | 0.19 | 0.13 | [-0.06, 0.45] | 1.49 | 0.137 + treatment | control | 2 | a | 0.00 | 0.13 | [-0.26, 0.25] | -0.01 | 0.991 + treatment | control | 1 | b | -0.18 | 0.12 | [-0.42, 0.06] | -1.45 | 0.147 + treatment | control | 2 | b | -0.05 | 0.12 | [-0.29, 0.19] | -0.40 | 0.691 + + Variable predicted: score + Predictors contrasted: grp + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model2, "grp", by = "time"), zap_small = TRUE, + table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | time | Difference | SE | 95% CI | t(992) | p + ------------------------------------------------------------------------------- + treatment | control | 1 | 0.01 | 0.09 | [-0.17, 0.18] | 0.09 | 0.931 + treatment | control | 2 | -0.02 | 0.09 | [-0.20, 0.15] | -0.28 | 0.780 + + Variable predicted: score + Predictors contrasted: grp + Predictors averaged over a balanced grid: x + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model2, c("grp", "time", "x='a'")), zap_small = TRUE, + table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(992) | p + -------------------------------------------------------------------------------- + control, 2 | control, 1 | 0.03 | 0.13 | [-0.23, 0.28] | 0.19 | 0.847 + treatment, 1 | control, 1 | 0.19 | 0.13 | [-0.06, 0.45] | 1.49 | 0.137 + treatment, 2 | control, 1 | 0.02 | 0.13 | [-0.23, 0.27] | 0.19 | 0.850 + treatment, 1 | control, 2 | 0.17 | 0.13 | [-0.09, 0.43] | 1.26 | 0.207 + treatment, 2 | control, 2 | 0.00 | 0.13 | [-0.26, 0.25] | -0.01 | 0.991 + treatment, 2 | treatment, 1 | -0.17 | 0.13 | [-0.42, 0.08] | -1.32 | 0.187 + + Variable predicted: score + Predictors contrasted: grp, time, x='a' + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model2, c("grp", "time=1"), by = "x"), zap_small = TRUE, + table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | x | Difference | SE | 95% CI | t(992) | p + ---------------------------------------------------------------------------- + treatment | control | a | 0.19 | 0.13 | [-0.06, 0.45] | 1.49 | 0.137 + treatment | control | b | -0.18 | 0.12 | [-0.42, 0.06] | -1.45 | 0.147 + + Variable predicted: score + Predictors contrasted: grp, time=1 + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model2, "grp", by = c("time", "x='a'")), zap_small = TRUE, + table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | time | x | Difference | SE | 95% CI | t(992) | p + ----------------------------------------------------------------------------------- + treatment | control | 1 | a | 0.19 | 0.13 | [-0.06, 0.45] | 1.49 | 0.137 + treatment | control | 2 | a | 0.00 | 0.13 | [-0.26, 0.25] | -0.01 | 0.991 + + Variable predicted: score + Predictors contrasted: grp + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model2, "time=c(1,2)", by = "grp"), zap_small = TRUE, + table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | grp | Difference | SE | 95% CI | t(994) | p + -------------------------------------------------------------------------------- + 2 | 1 | control | 0.14 | 0.11 | [-0.08, 0.36] | 1.24 | 0.216 + 2 | 1 | treatment | -0.07 | 0.11 | [-0.28, 0.14] | -0.63 | 0.529 + + Variable predicted: score + Predictors contrasted: time=c(1,2) + p-values are uncorrected. + +--- + + Code + print(estimate_contrasts(model2, c("grp", "time=2")), zap_small = TRUE, + table_width = Inf) + Output + Conditional Contrasts + + Level1 | Level2 | Difference | SE | 95% CI | t(994) | p + ------------------------------------------------------------------------ + treatment | control | -0.15 | 0.11 | [-0.36, 0.05] | -1.47 | 0.143 + + Variable predicted: score + Predictors contrasted: grp, time=2 + p-values are uncorrected. + diff --git a/tests/testthat/_snaps/plot-flexible_numeric/plot-auto-numeric-by-1.svg b/tests/testthat/_snaps/linux/plot-flexible_numeric/plot-auto-numeric-by-1.svg similarity index 100% rename from tests/testthat/_snaps/plot-flexible_numeric/plot-auto-numeric-by-1.svg rename to tests/testthat/_snaps/linux/plot-flexible_numeric/plot-auto-numeric-by-1.svg diff --git a/tests/testthat/_snaps/plot-flexible_numeric/plot-auto-numeric-by-2.svg b/tests/testthat/_snaps/linux/plot-flexible_numeric/plot-auto-numeric-by-2.svg similarity index 100% rename from tests/testthat/_snaps/plot-flexible_numeric/plot-auto-numeric-by-2.svg rename to tests/testthat/_snaps/linux/plot-flexible_numeric/plot-auto-numeric-by-2.svg diff --git a/tests/testthat/_snaps/residualize_over_grid/plot-show-residuals-1.svg b/tests/testthat/_snaps/linux/residualize_over_grid/plot-show-residuals-1.svg similarity index 100% rename from tests/testthat/_snaps/residualize_over_grid/plot-show-residuals-1.svg rename to tests/testthat/_snaps/linux/residualize_over_grid/plot-show-residuals-1.svg diff --git a/tests/testthat/_snaps/residualize_over_grid/plot-show-residuals-2.svg b/tests/testthat/_snaps/linux/residualize_over_grid/plot-show-residuals-2.svg similarity index 100% rename from tests/testthat/_snaps/residualize_over_grid/plot-show-residuals-2.svg rename to tests/testthat/_snaps/linux/residualize_over_grid/plot-show-residuals-2.svg diff --git a/tests/testthat/_snaps/residualize_over_grid/plot-show-residuals-3.svg b/tests/testthat/_snaps/linux/residualize_over_grid/plot-show-residuals-3.svg similarity index 100% rename from tests/testthat/_snaps/residualize_over_grid/plot-show-residuals-3.svg rename to tests/testthat/_snaps/linux/residualize_over_grid/plot-show-residuals-3.svg diff --git a/tests/testthat/_snaps/windows/estimate_contrasts.md b/tests/testthat/_snaps/windows/estimate_contrasts.md index 85910abba..de0d98ac4 100644 --- a/tests/testthat/_snaps/windows/estimate_contrasts.md +++ b/tests/testthat/_snaps/windows/estimate_contrasts.md @@ -256,6 +256,14 @@ Code print(estimate_contrasts(model, contrast = c("mined", "spp"), backend = "marginaleffects"), zap_small = TRUE, table_width = Inf) + Message + Some confidence intervals extend beyond plausible bounds. For poisson + models, `predict = "response"` generally yields less biased point + estimates, but symmetric confidence intervals can fall outside the valid + parameter range. Consider using `predict = "inverse_link"` with + `bias_correction = TRUE` instead. Optionally, you can also set + `residual_variance` to a sensible value to specify the assumed variance. + Set `verbose = FALSE` to silent this message (and other warnings). Output Conditional Contrasts diff --git a/tests/testthat/_snaps/windows/plot-flexible_numeric/plot-auto-numeric-by-1.svg b/tests/testthat/_snaps/windows/plot-flexible_numeric/plot-auto-numeric-by-1.svg new file mode 100644 index 000000000..be4f9009e --- /dev/null +++ b/tests/testthat/_snaps/windows/plot-flexible_numeric/plot-auto-numeric-by-1.svg @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +-20 +-10 +0 +10 +20 + + + + + + + + + + + + +-3 +-2 +-1 +0 +1 +2 +3 +x1 +Mean of y + +x2 + + + + + + + + + + + + + +-3 +-2 +-1 +0 +1 +2 +plot-auto-numeric-by-1 + + diff --git a/tests/testthat/_snaps/windows/plot-flexible_numeric/plot-auto-numeric-by-2.svg b/tests/testthat/_snaps/windows/plot-flexible_numeric/plot-auto-numeric-by-2.svg new file mode 100644 index 000000000..1083a96da --- /dev/null +++ b/tests/testthat/_snaps/windows/plot-flexible_numeric/plot-auto-numeric-by-2.svg @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +-10 +-5 +0 +5 +10 + + + + + + + + + + + + +-3 +-2 +-1 +0 +1 +2 +3 +x1 +Mean of y + +x2 + + + + + + + + + +-0.93 +0.07 +1.08 +plot-auto-numeric-by-2 + + diff --git a/tests/testthat/_snaps/windows/residualize_over_grid/plot-show-residuals-1.svg b/tests/testthat/_snaps/windows/residualize_over_grid/plot-show-residuals-1.svg new file mode 100644 index 000000000..2b55f2cab --- /dev/null +++ b/tests/testthat/_snaps/windows/residualize_over_grid/plot-show-residuals-1.svg @@ -0,0 +1,384 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +0 +10 +20 +30 +40 +50 + + + + + + + + + +8 +10 +12 +x +Mean of y + +z + + + + + + + + + + + + +-1.09 +-0.06 +0.98 +plot-show_residuals-1 + + diff --git a/tests/testthat/_snaps/windows/residualize_over_grid/plot-show-residuals-2.svg b/tests/testthat/_snaps/windows/residualize_over_grid/plot-show-residuals-2.svg new file mode 100644 index 000000000..b39dc5bd1 --- /dev/null +++ b/tests/testthat/_snaps/windows/residualize_over_grid/plot-show-residuals-2.svg @@ -0,0 +1,407 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +0 +10 +20 +30 +40 +50 + + + + + + + + + +8 +10 +12 +x +Mean of y + +z + + + + + + + +-2 +0 +2 +plot-show_residuals-2 + + diff --git a/tests/testthat/_snaps/windows/residualize_over_grid/plot-show-residuals-3.svg b/tests/testthat/_snaps/windows/residualize_over_grid/plot-show-residuals-3.svg new file mode 100644 index 000000000..acc3e64be --- /dev/null +++ b/tests/testthat/_snaps/windows/residualize_over_grid/plot-show-residuals-3.svg @@ -0,0 +1,238 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +4 +5 +6 +7 +8 + + + + + + + + + + + +2.0 +2.5 +3.0 +3.5 +4.0 +4.5 +Sepal.Width +Mean of Sepal.Length + +Species + + + + + + + + + + + + +setosa +versicolor +virginica +plot-show_residuals-3 + + diff --git a/tests/testthat/test-backtransform_invlink.R b/tests/testthat/test-backtransform_invlink.R index 7b7838dac..b8c1f2849 100644 --- a/tests/testthat/test-backtransform_invlink.R +++ b/tests/testthat/test-backtransform_invlink.R @@ -37,9 +37,27 @@ test_that("estimate_means correct inverse link for glm", { expect_true(all(out$CI_high >= 0 & out$CI_high <= 1)) # response scale - some CI < 0 - out <- estimate_means(m, by = c("var1", "var2"), estimate = "population") + expect_message( + { + out <- estimate_means(m, by = c("var1", "var2"), estimate = "population") + }, + regex = "Some confidence intervals" + ) expect_true(sum(out$CI_low < 0) > 0) expect_true(sum(out$CI_high > 1) > 0) + + expect_no_message(estimate_means( + m, + by = c("var1", "var2"), + estimate = "population", + predict = "inverse_link" + )) + expect_no_message(estimate_means( + m, + by = c("var1", "var2"), + estimate = "population", + verbose = FALSE + )) }) diff --git a/tests/testthat/test-estimate_contrasts.R b/tests/testthat/test-estimate_contrasts.R index 6b5e09c58..75f02991c 100644 --- a/tests/testthat/test-estimate_contrasts.R +++ b/tests/testthat/test-estimate_contrasts.R @@ -359,7 +359,7 @@ test_that("estimate_contrasts - Frequentist, duplicated levels", { zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -367,7 +367,7 @@ test_that("estimate_contrasts - Frequentist, duplicated levels", { zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) dat <- iris @@ -1091,7 +1091,7 @@ test_that("estimate_contrasts - filtering works", { table_width = Inf, zap_small = TRUE ), - variant = "windows" + variant = snapshot_variant() ) fit <- lm(neg_c_7 ~ e16sex + c161sex * c172code, data = efc) @@ -1106,7 +1106,7 @@ test_that("estimate_contrasts - filtering works", { table_width = Inf, zap_small = TRUE ), - variant = "windows" + variant = snapshot_variant() ) fit <- lm(neg_c_7 ~ barthtot + c161sex + c172code, data = efc) @@ -1116,7 +1116,7 @@ test_that("estimate_contrasts - filtering works", { table_width = Inf, zap_small = TRUE ), - variant = "windows" + variant = snapshot_variant() ) # error expect_error( @@ -1131,7 +1131,7 @@ test_that("estimate_contrasts - filtering works", { table_width = Inf, zap_small = TRUE ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1139,7 +1139,7 @@ test_that("estimate_contrasts - filtering works", { table_width = Inf, zap_small = TRUE ), - variant = "windows" + variant = snapshot_variant() ) fit <- lm(neg_c_7 ~ e16sex * barthtot * c172code, data = efc) expect_snapshot( @@ -1153,7 +1153,7 @@ test_that("estimate_contrasts - filtering works", { table_width = Inf, zap_small = TRUE ), - variant = "windows" + variant = snapshot_variant() ) # error expect_error( @@ -1173,7 +1173,7 @@ test_that("estimate_contrasts - simple contrasts and with - in levels works", { estimate_contrasts(model, "Species", backend = "marginaleffects"), table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) data(coffee_data, package = "modelbased") @@ -1184,7 +1184,7 @@ test_that("estimate_contrasts - simple contrasts and with - in levels works", { zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( @@ -1198,7 +1198,7 @@ test_that("estimate_contrasts - simple contrasts and with - in levels works", { zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) data(Salamanders, package = "glmmTMB") @@ -1217,7 +1217,7 @@ test_that("estimate_contrasts - simple contrasts and with - in levels works", { zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1230,7 +1230,7 @@ test_that("estimate_contrasts - simple contrasts and with - in levels works", { zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) }) @@ -1434,7 +1434,7 @@ test_that("estimate_contrasts - examples from docs work as intendec", { zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1442,7 +1442,7 @@ test_that("estimate_contrasts - examples from docs work as intendec", { zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1450,7 +1450,7 @@ test_that("estimate_contrasts - examples from docs work as intendec", { zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) }) @@ -1473,7 +1473,7 @@ test_that("estimate_contrasts - test all combinations of contrast and by, with f zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1481,7 +1481,7 @@ test_that("estimate_contrasts - test all combinations of contrast and by, with f zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1489,7 +1489,7 @@ test_that("estimate_contrasts - test all combinations of contrast and by, with f zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1497,7 +1497,7 @@ test_that("estimate_contrasts - test all combinations of contrast and by, with f zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1505,7 +1505,7 @@ test_that("estimate_contrasts - test all combinations of contrast and by, with f zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1513,7 +1513,7 @@ test_that("estimate_contrasts - test all combinations of contrast and by, with f zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1521,7 +1521,7 @@ test_that("estimate_contrasts - test all combinations of contrast and by, with f zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) set.seed(123) @@ -1539,7 +1539,7 @@ test_that("estimate_contrasts - test all combinations of contrast and by, with f zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) expect_snapshot( print( @@ -1547,7 +1547,7 @@ test_that("estimate_contrasts - test all combinations of contrast and by, with f zap_small = TRUE, table_width = Inf ), - variant = "windows" + variant = snapshot_variant() ) }) diff --git a/tests/testthat/test-g_computation.R b/tests/testthat/test-g_computation.R index 493edaa23..3ac497c7c 100644 --- a/tests/testthat/test-g_computation.R +++ b/tests/testthat/test-g_computation.R @@ -5,7 +5,6 @@ skip_on_os("mac") test_that("estimate_contrasts - ATT and ATU", { skip_if_not_installed("Rdatasets") - skip_on_os("linux") dat <- marginaleffects::get_dataset("lottery") dat <- subset(dat, win_big == 1 | win == 0) @@ -63,10 +62,10 @@ test_that("estimate_contrasts - ATT and ATU", { ) expect_equal(out1$estimate, out2$Difference, tolerance = 1e-4) - # error + # error - updated error msg expect_error( estimate_contrasts(mod, "win_big", newdata = subset(dat, win_big == 1)), - regex = "It seems that not all" + regex = "No rows returned" ) }) diff --git a/tests/testthat/test-offset.R b/tests/testthat/test-offset.R index 4c29a780b..3152b8849 100644 --- a/tests/testthat/test-offset.R +++ b/tests/testthat/test-offset.R @@ -35,9 +35,19 @@ test_that("offset works", { expect_silent({ out1 <- estimate_means(moff, "x", offset = 100) }) - expect_silent({ - out2 <- estimate_means(moff, "x", estimate = "average", offset = 100) - }) + expect_silent(estimate_means( + moff, + "x", + estimate = "average", + offset = 100, + verbose = FALSE + )) + expect_message( + { + out2 <- estimate_means(moff, "x", estimate = "average", offset = 100) + }, + regex = "Some confidence intervals" + ) expect_equal(out1$Mean, c(664.68547, 1023.27456, 1474.41949), tolerance = 1e-3) expect_equal(out2$Mean, c(664.68547, 1023.27456, 1474.41949), tolerance = 1e-3) @@ -58,9 +68,12 @@ test_that("offset works", { out2 <- estimate_means(moff, "x", estimate = "population", offset = 100) expect_equal(out1$estimate, out2$Mean, tolerance = 1e-4) - expect_silent({ - out3 <- estimate_means(moff, c("x", "offset_1 = 100"), estimate = "population") - }) + expect_message( + { + out3 <- estimate_means(moff, c("x", "offset_1 = 100"), estimate = "population") + }, + regex = "Some confidence intervals" + ) expect_equal(out3$Mean, out2$Mean, tolerance = 1e-4) set.seed(1) diff --git a/tests/testthat/test-plot-flexible_numeric.R b/tests/testthat/test-plot-flexible_numeric.R index 9ae349f99..d0ae82667 100644 --- a/tests/testthat/test-plot-flexible_numeric.R +++ b/tests/testthat/test-plot-flexible_numeric.R @@ -1,4 +1,4 @@ -skip_on_os(c("mac", "solaris", "linux")) +skip_on_os(c("mac", "solaris")) skip_if_not_installed("ggplot2") skip_if_not_installed("see") skip_if_not_installed("vdiffr") @@ -17,12 +17,14 @@ test_that("plot 2nd by is numeric", { pr <- estimate_means(model, c("x1", "x2")) vdiffr::expect_doppelganger( "plot-auto-numeric-by-1", - plot(pr) + plot(pr), + variant = snapshot_variant() ) pr <- estimate_means(model, c("x1", "x2 = [sd]")) vdiffr::expect_doppelganger( "plot-auto-numeric-by-2", - plot(pr) + plot(pr), + variant = snapshot_variant() ) }) diff --git a/tests/testthat/test-residualize_over_grid.R b/tests/testthat/test-residualize_over_grid.R index 3c2ba9fd9..86a3628b5 100644 --- a/tests/testthat/test-residualize_over_grid.R +++ b/tests/testthat/test-residualize_over_grid.R @@ -1,4 +1,4 @@ -skip_on_os(c("mac", "solaris", "linux")) +skip_on_os(c("mac", "solaris")) skip_if_not_installed("ggplot2") skip_if_not_installed("see") skip_if_not_installed("vdiffr") @@ -20,10 +20,7 @@ test_that("residualize_over_grid", { expect_equal(sum(out$Predicted), 875.7863, tolerance = 1e-2) pr <- estimate_relation(model, by = c("Sepal.Width", "Species")) - expect_error( - residualize_over_grid(pr, model), - regex = "Grid for partial" - ) + expect_error(residualize_over_grid(pr, model), regex = "Grid for partial") }) @@ -40,13 +37,15 @@ test_that("plots show_resisuals", { est <- estimate_means(m, c("x", "z=[sd]")) vdiffr::expect_doppelganger( "plot-show_residuals-1", - plot(est, show_residuals = TRUE) + plot(est, show_residuals = TRUE), + variant = snapshot_variant() ) est <- estimate_means(m, c("x", "z")) vdiffr::expect_doppelganger( "plot-show_residuals-2", - plot(est, show_residuals = TRUE) + plot(est, show_residuals = TRUE), + variant = snapshot_variant() ) data(iris) @@ -55,6 +54,7 @@ test_that("plots show_resisuals", { pr <- estimate_means(model, c("Sepal.Width", "Species")) vdiffr::expect_doppelganger( "plot-show_residuals-3", - plot(pr, show_residuals = TRUE) + plot(pr, show_residuals = TRUE), + variant = snapshot_variant() ) }) diff --git a/tests/testthat/test-scoping_issues.R b/tests/testthat/test-scoping_issues.R index 87b83a5e1..d88d9ad62 100644 --- a/tests/testthat/test-scoping_issues.R +++ b/tests/testthat/test-scoping_issues.R @@ -1,4 +1,4 @@ -skip_on_os(c("mac", "linux")) +skip_on_os("mac") skip_if_not_installed("marginaleffects", minimum_version = "0.29.0") skip_if_not_installed("withr") diff --git a/vignettes/practical_context_effect.Rmd b/vignettes/practical_context_effect.Rmd index d50e2e15c..2fa04d5e6 100644 --- a/vignettes/practical_context_effect.Rmd +++ b/vignettes/practical_context_effect.Rmd @@ -296,7 +296,7 @@ The output now displays the mathematical difference in the size of the context e This pairwise comparison formally solidifies our previous suspicion: The buffering effect of higher education is statistically robust. -It proves that the "chronic penalty" for long-term psychological burden does not hit everyone equally. The structural or psychological advantages possessed by the highly educated group (such as better access to support networks, financial stability, or coping resources) create a mathematically significant difference in how chronic distress is processed. Compared directly to the middle-educated tier—who bear the full weight of the context effect—highly educated patients are significantly better protected from the cumulative "wear and tear" of a chronically high baseline burden. +It proves that the "chronic penalty" for long-term psychological burden does not hit everyone equally. The structural or psychological advantages possessed by the highly educated group (such as better access to support networks, financial stability, or coping resources) create a mathematically significant difference in how chronic distress is processed. Compared directly to the middle-educated tier - who bear the full weight of the context effect - highly educated patients are significantly better protected from the cumulative "wear and tear" of a chronically high baseline burden. # Disclaimer