R/abc_posterior.R

Defines functions abc_posterior_bootstrap

Documented in abc_posterior_bootstrap

#' Bootstrap resample ABC posterior samples
#'
#' @param abc_result An abc object from \code{\link[abc]{abc}}
#' @param n_samples Number of bootstrap samples to draw (default 1000)
#' @param replace Logical, whether to sample with replacement (default TRUE)
#' @return Data frame of bootstrapped parameter values
#' @examples
#' # Load an example abc output, you should generate it by applying ABC to your data
#' # check abc_abc for details on fitting ABC models
#' rdm_minimal_example <- system.file("extdata", "rdm_minimal", package = "eam")
#' abc_model <- readRDS(file.path(rdm_minimal_example, "abc", "abc_neuralnet_model.rds"))
#'
#' # Bootstrap resample posterior parameters
#' posterior_params <- abc_posterior_bootstrap(
#'   abc_model,
#'   n_samples = 100
#' )
#' 
#' # View the first few rows of the bootstrapped posterior parameters
#' head(posterior_params)
#' @export
abc_posterior_bootstrap <- function(
    abc_result,
    n_samples,
    replace = TRUE) {
  if (!inherits(abc_result, "abc")) {
    stop("abc_result must be of class 'abc'")
  }

  params <- extract_abc_param_values(abc_result)

  # Check if we have enough samples for bootstrap without replacement
  n_available <- nrow(params)
  if (!replace && n_samples > n_available) {
    stop(
      "n_samples (", n_samples, ") cannot be larger than ",
      "available posterior samples (", n_available, ") when replace = FALSE"
    )
  }

  # Draw bootstrap sample indices
  sample_idx <- sample(n_available, n_samples, replace = replace)

  # Return bootstrapped parameter data frame
  as.data.frame(params[sample_idx, , drop = FALSE])
}

Try the eam package in your browser

Any scripts or data that you put into this service are public.

eam documentation built on March 29, 2026, 5:07 p.m.