Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
9 changes: 9 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
31 changes: 21 additions & 10 deletions R/estimate_contrasts.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 41 additions & 1 deletion R/get_marginalmeans.R
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand Down
11 changes: 10 additions & 1 deletion R/get_marginaltrends.R
Original file line number Diff line number Diff line change
Expand Up @@ -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? -----------------------------------------------
Expand Down
31 changes: 21 additions & 10 deletions man/estimate_contrasts.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 21 additions & 10 deletions man/get_emmeans.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

59 changes: 59 additions & 0 deletions tests/testthat/test-bootstrapping.R
Original file line number Diff line number Diff line change
@@ -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)
})
Loading