From 0d4849f9ad7ed06b6cdafee0e81886138f581d25 Mon Sep 17 00:00:00 2001 From: Daniel Date: Sun, 29 Nov 2026 00:38:45 +0100 Subject: [PATCH 1/2] Bootstrapping for `estimate_slopes()`? Fixes #727 --- DESCRIPTION | 2 +- R/estimate_contrasts.R | 31 ++++++++++----- R/get_marginalmeans.R | 42 +++++++++++++++++++- R/get_marginaltrends.R | 11 +++++- man/estimate_contrasts.Rd | 31 ++++++++++----- man/get_emmeans.Rd | 31 ++++++++++----- tests/testthat/test-bootstrapping.R | 59 +++++++++++++++++++++++++++++ 7 files changed, 174 insertions(+), 33 deletions(-) create mode 100644 tests/testthat/test-bootstrapping.R diff --git a/DESCRIPTION b/DESCRIPTION index 34c93dc3a..633386d34 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: modelbased Title: Estimation of Model-Based Predictions, Contrasts and Means -Version: 0.19.0.4 +Version: 0.19.0.5 Authors@R: c(person(given = "Dominique", family = "Makowski", diff --git a/R/estimate_contrasts.R b/R/estimate_contrasts.R index fd356c267..de5609322 100644 --- a/R/estimate_contrasts.R +++ b/R/estimate_contrasts.R @@ -121,16 +121,27 @@ #' `"hedges.g"`, `"cohens.d.sigma"`, `"r"`, or `"akp.robust.d"`. See `effect.type` #' argument of [`bootES::bootES()`] for details. If not specified, defaults to #' `"cohens.d"`. -#' @param iterations This argument has two distinct effects, depending on the -#' context. When `effectsize = "boot"`, it defines the number of bootstrap -#' resamples used to calculate the effect size (via [`bootES::bootES()`]), and -#' defaults to `200` in this case. For Bayesian models used in `estimate_means()`, -#' `estimate_slopes()`, or `estimate_contrasts()` (and when -#' `backend = "marginaleffects"`), it is passed to the `ndraws` argument of the -#' related `marginaleffects` functions, and defines the number of posterior -#' draws to sample from. If `NULL` (the default), all draws are used. Note -#' that `ndraws` currently only has an effect for Bayesian models fit with -#' **brms** or **MCMCglmm**. +#' @param iterations This argument has three distinct effects, depending on the +#' context: +#' - When `effectsize = "boot"`, it defines the number of bootstrap resamples +#' used to calculate the effect size (via [`bootES::bootES()`]), defaulting +#' to `200`. +#' - For Bayesian models in `estimate_means()`, `estimate_slopes()`, or +#' `estimate_contrasts()` (with `backend = "marginaleffects"`), it is passed +#' to the `ndraws` argument of the underlying `marginaleffects` functions and +#' defines the number of posterior draws to sample. +#' - For non-Bayesian models, setting `iterations` to a non-`NULL` value +#' triggers an additional call to `marginaleffects::inferences()` (with `R = +#' iterations`) to compute bootstrapped estimates. In this case, you must also +#' specify the `method` argument, which can be one of `"delta"`, `"boot"`, +#' `"fwb"`, `"rsample"`, `"simulation"`, `"conformal_split"`, +#' `"conformal_cv+"`, `"conformal_quantile"`, or `"conformal_full"`. +#' +#' Defaults to `NULL` (for Bayesian models, all posterior draws are used; for +#' non-Bayesian models, no bootstrapping is performed). Note that `ndraws` +#' currently only has an effect for Bayesian models fit with **brms** or +#' **MCMCglmm**. +#' #' @inheritParams estimate_means #' #' @inherit estimate_means details diff --git a/R/get_marginalmeans.R b/R/get_marginalmeans.R index 859f1bf37..c0bd7486f 100644 --- a/R/get_marginalmeans.R +++ b/R/get_marginalmeans.R @@ -250,16 +250,25 @@ get_marginalmeans <- function( } # bayesian models: number of posterior draws to use, passed to `ndraws` - if (!is.null(iterations)) { + if (!is.null(iterations) && model_info$is_bayesian) { fun_args$ndraws <- iterations } + # reserved for "inferences()", i.e. when we have "iterations" + fun_args$method <- NULL + # Fourth step: compute marginal means --------------------------------------- # --------------------------------------------------------------------------- # we can use this function for contrasts as well, # just need to add "hypothesis" argument means <- .call_marginaleffects(fun_args, post_process, verbose) + + # bayesian models: number of posterior draws to use, passed to `ndraws` + if (!is.null(iterations) && !model_info$is_bayesian) { + means <- .marginaleffects_inferences(means, iterations, dots) + } + vcov_means <- .safe(stats::vcov(means)) # check for valid bounds, when model is glm and predict = "response" @@ -554,6 +563,37 @@ get_marginalmeans <- function( } +# bootstrapping for non-Bayesian ---------------------------------------------- + +.marginaleffects_inferences <- function(x, iterations, dots) { + # remove unused arguments + dots["df"] <- NULL + # check if "method" was provided + if (is.null(dots$method)) { + insight::format_error( + "If bootstrapping (via `iterations`) is requested, you must specify the `method` argument." + ) + } + # validate input + dots$method <- insight::validate_argument( + dots$method, + c( + "delta", + "boot", + "fwb", + "rsample", + "simulation", + "conformal_split", + "conformal_cv+", + "conformal_quantile", + "conformal_full" + ) + ) + + do.call(marginaleffects::inferences, c(list(x, R = iterations), dots)) +} + + # handle attributes ----------------------------------------------------------- # we have following attributes for modelbased-objects: diff --git a/R/get_marginaltrends.R b/R/get_marginaltrends.R index febcf994c..e2a7d4b72 100644 --- a/R/get_marginaltrends.R +++ b/R/get_marginaltrends.R @@ -148,15 +148,24 @@ get_marginaltrends <- function( } # bayesian models: number of posterior draws to use, passed to `ndraws` - if (!is.null(iterations)) { + if (!is.null(iterations) && model_info$is_bayesian) { fun_args$ndraws <- iterations } + # reserved for "inferences()", i.e. when we have "iterations" + fun_args$method <- NULL + # Third step: compute marginal slopes --------------------------------------- # --------------------------------------------------------------------------- # Compute stuff estimated <- suppressWarnings(do.call(marginaleffects::avg_slopes, fun_args)) + + # non-bayesian models: calculate bootstraps based on `inference()` + if (!is.null(iterations) && !model_info$is_bayesian) { + estimated <- .marginaleffects_inferences(estimated, iterations, dots) + } + vcov_slopes <- .safe(stats::vcov(estimated)) # any subsequent comparisons? ----------------------------------------------- diff --git a/man/estimate_contrasts.Rd b/man/estimate_contrasts.Rd index 74b1ec52d..9969ef167 100644 --- a/man/estimate_contrasts.Rd +++ b/man/estimate_contrasts.Rd @@ -323,16 +323,27 @@ size will be computed. Effect sizes are only available for Gaussian models without random effects, and (only for \code{"emmeans"}) for ordinal models on the latent scale (see 'Details').} -\item{iterations}{This argument has two distinct effects, depending on the -context. When \code{effectsize = "boot"}, it defines the number of bootstrap -resamples used to calculate the effect size (via \code{\link[bootES:bootES]{bootES::bootES()}}), and -defaults to \code{200} in this case. For Bayesian models used in \code{estimate_means()}, -\code{estimate_slopes()}, or \code{estimate_contrasts()} (and when -\code{backend = "marginaleffects"}), it is passed to the \code{ndraws} argument of the -related \code{marginaleffects} functions, and defines the number of posterior -draws to sample from. If \code{NULL} (the default), all draws are used. Note -that \code{ndraws} currently only has an effect for Bayesian models fit with -\strong{brms} or \strong{MCMCglmm}.} +\item{iterations}{This argument has three distinct effects, depending on the +context: +\itemize{ +\item When \code{effectsize = "boot"}, it defines the number of bootstrap resamples +used to calculate the effect size (via \code{\link[bootES:bootES]{bootES::bootES()}}), defaulting +to \code{200}. +\item For Bayesian models in \code{estimate_means()}, \code{estimate_slopes()}, or +\code{estimate_contrasts()} (with \code{backend = "marginaleffects"}), it is passed +to the \code{ndraws} argument of the underlying \code{marginaleffects} functions and +defines the number of posterior draws to sample. +\item For non-Bayesian models, setting \code{iterations} to a non-\code{NULL} value +triggers an additional call to \code{marginaleffects::inferences()} (with \code{R = iterations}) to compute bootstrapped estimates. In this case, you must also +specify the \code{method} argument, which can be one of \code{"delta"}, \code{"boot"}, +\code{"fwb"}, \code{"rsample"}, \code{"simulation"}, \code{"conformal_split"}, +\code{"conformal_cv+"}, \code{"conformal_quantile"}, or \code{"conformal_full"}. +} + +Defaults to \code{NULL} (for Bayesian models, all posterior draws are used; for +non-Bayesian models, no bootstrapping is performed). Note that \code{ndraws} +currently only has an effect for Bayesian models fit with \strong{brms} or +\strong{MCMCglmm}.} \item{es_type}{Specifies the type of effect-size measure to estimate when using \code{effectsize = "boot"}. One of \code{"unstandardized"}, \code{"cohens.d"}, diff --git a/man/get_emmeans.Rd b/man/get_emmeans.Rd index 0d061450b..21687e6cc 100644 --- a/man/get_emmeans.Rd +++ b/man/get_emmeans.Rd @@ -387,16 +387,27 @@ term (for example \code{comparison = ~pairwise | group}), in each group. In methods, \code{"tukey"} and \code{"sidak"} are applied to the slopes, and other methods are ignored.} -\item{iterations}{This argument has two distinct effects, depending on the -context. When \code{effectsize = "boot"}, it defines the number of bootstrap -resamples used to calculate the effect size (via \code{\link[bootES:bootES]{bootES::bootES()}}), and -defaults to \code{200} in this case. For Bayesian models used in \code{estimate_means()}, -\code{estimate_slopes()}, or \code{estimate_contrasts()} (and when -\code{backend = "marginaleffects"}), it is passed to the \code{ndraws} argument of the -related \code{marginaleffects} functions, and defines the number of posterior -draws to sample from. If \code{NULL} (the default), all draws are used. Note -that \code{ndraws} currently only has an effect for Bayesian models fit with -\strong{brms} or \strong{MCMCglmm}.} +\item{iterations}{This argument has three distinct effects, depending on the +context: +\itemize{ +\item When \code{effectsize = "boot"}, it defines the number of bootstrap resamples +used to calculate the effect size (via \code{\link[bootES:bootES]{bootES::bootES()}}), defaulting +to \code{200}. +\item For Bayesian models in \code{estimate_means()}, \code{estimate_slopes()}, or +\code{estimate_contrasts()} (with \code{backend = "marginaleffects"}), it is passed +to the \code{ndraws} argument of the underlying \code{marginaleffects} functions and +defines the number of posterior draws to sample. +\item For non-Bayesian models, setting \code{iterations} to a non-\code{NULL} value +triggers an additional call to \code{marginaleffects::inferences()} (with \code{R = iterations}) to compute bootstrapped estimates. In this case, you must also +specify the \code{method} argument, which can be one of \code{"delta"}, \code{"boot"}, +\code{"fwb"}, \code{"rsample"}, \code{"simulation"}, \code{"conformal_split"}, +\code{"conformal_cv+"}, \code{"conformal_quantile"}, or \code{"conformal_full"}. +} + +Defaults to \code{NULL} (for Bayesian models, all posterior draws are used; for +non-Bayesian models, no bootstrapping is performed). Note that \code{ndraws} +currently only has an effect for Bayesian models fit with \strong{brms} or +\strong{MCMCglmm}.} } \description{ These functions are convenient wrappers around the \strong{emmeans} and the diff --git a/tests/testthat/test-bootstrapping.R b/tests/testthat/test-bootstrapping.R new file mode 100644 index 000000000..1d7f0e529 --- /dev/null +++ b/tests/testthat/test-bootstrapping.R @@ -0,0 +1,59 @@ +skip_on_cran() +skip_if_not_installed("marginaleffects", minimum_version = "0.29.0") +skip_on_os("mac") + +test_that("estimate_slopes, bootstrapped", { + data(iris) + model <- lm(Sepal.Width ~ Species * Petal.Length, data = iris) + + expect_error( + estimate_slopes(model, slope = "Petal.Length", iterations = 50), + regex = "If bootstrapping", + fixed = TRUE + ) + expect_error( + estimate_slopes(model, slope = "Petal.Length", method = "abc", iterations = 50), + regex = "Invalid option", + fixed = TRUE + ) + + set.seed(123) + slopes <- estimate_slopes( + model, + slope = "Petal.Length", + iterations = 50, + method = "boot" + ) + expect_equal(slopes$Coefficient, 0.33218, tolerance = 1e-3) + + set.seed(123) + slopes <- estimate_slopes( + model, + slope = "Petal.Length", + by = "Species", + iterations = 50, + method = "boot" + ) + expect_equal(slopes$Coefficient, c(0.38787, 0.37431, 0.23435), tolerance = 1e-3) +}) + + +test_that("estimate_means, bootstrapped", { + data(iris) + model <- lm(Sepal.Width ~ Species * Petal.Length, data = iris) + + expect_error( + estimate_means(model, "Species", iterations = 50), + regex = "If bootstrapping", + fixed = TRUE + ) + expect_error( + estimate_means(model, "Species", method = "abc", iterations = 50), + regex = "Invalid option", + fixed = TRUE + ) + + set.seed(123) + means <- estimate_means(model, "Species", iterations = 50, method = "boot") + expect_equal(means$Coefficient, c(4.31856, 2.5821, 2.55358), tolerance = 1e-3) +}) From 5fa97f576feb563a51bd3a9511b229d4a91284d0 Mon Sep 17 00:00:00 2001 From: Daniel Date: Sun, 29 Nov 2026 00:40:49 +0100 Subject: [PATCH 2/2] news --- NEWS.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/NEWS.md b/NEWS.md index 235d81d2f..feed6fb9d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,14 @@ # modelbased (devel) +## Changes + +* `estimate_means()`, `estimate_slopes()`, and `estimate_contrasts()` now + support bootstrapped and simulation-based inference for non-Bayesian models + (when `backend = "marginaleffects"`). Setting `iterations` to a numeric value + along with `method` (e.g., `"boot"`, `"fwb"`, `"rsample"`, `"simulation"`, or + conformal methods) invokes `marginaleffects::inferences()` to compute + resampling-based uncertainty intervals. + ## Bug fixes * `estimate_means()`, `estimate_contrasts()` and `estimate_slopes()` with