R/stage-2.R

Defines functions causal.estimate

Documented in causal.estimate

# ======================================================================================
# WMAP PACKAGE - STAGE 2: CAUSAL EFFECT ESIMTATION
# ======================================================================================

# This file contains the main user-facing function for estimating causal effects
# with bootstrapping-based confidence intervals

# ======================================================================================
# VERSION HISTORY
# ======================================================================================

# Version 1.3 - Refactoring & Improvements
#               * Added parallel bootstrapping
#               * Updated variable naming (output1 -> weights)
#               * Added roxygen2 documentation to all functions
#               * Chnaged all = to <- for assignments
#               * Added additional comments
#               * Removed commented-out legacy code
#               * Added outcome_model parameter: fits random forest on X, S, Z
#                 and substitutes predicted outcomes for observed Y

# ======================================================================================
# IMPORTS
# ======================================================================================

#' @importFrom zeallot %<-%
NULL

# ======================================================================================
# CAUSAL EFFECTS
# ======================================================================================

#' Estimate causal effects using FLEXOR, IC, or IGO methods
#'
#' This function estimates causal effects based on the specified pseudo-population method.
#' The FLEXOR method involves an iterative two-step procedure.
#'
#' @param S Vector of factor levels representing the study memberships. Takes values in \{1, ..., J\}.
#' @param Z Vector of factor levels representing the group memberships. Takes values in \{1, ..., K\}.
#' @param X Covariate matrix of \eqn{N} rows and \eqn{p} columns.
#' @param Y Matrix of \eqn{L} outcomes, with dimensions \eqn{N \times L}.
#' @param B Number of bootstrap samples for variance estimation. Default is 0 (point estimates only).
#' @param method Pseudo-population method, i.e., weighting method. Take values in \code{FLEXOR}, \code{IC}, or \code{IGO}.
#' @param seed Seed for random number generation. Default is \code{NULL}.
#' @param naturalGroupProp Relevant only for FLEXOR method: a fixed user-specified probability vector \eqn{\theta}.
#' @param num.random Relevant only for FLEXOR method: number of random starting points of \eqn{\gamma} in the two-step iterative procedure. Default is 40.
#' @param gammaMin Relevant only for FLEXOR method: Lower bound for each \eqn{\gamma_s} in the two-step iterative procedure. Default is 0.001.
#' @param gammaMax Relevant only for FLEXOR method: Upper bound for each \eqn{\gamma_s} in the two-step iterative procedure. Default is 0.999.
#' @param verbose Logical; if \code{TRUE} (default), displays progress messages during computation to the console. Set to \code{FALSE} to suppress these messages.
#' @param parallel Logical; if TRUE, use parallel processing for bootstrap (default: FALSE)
#' @param n_cores Number of cores to use for parallel bootstrap (default: availableCores() - 1). Only used if parallel = TRUE.
#' @param outcome_model Logical; if TRUE, fits a random forest on X, S, Z and substitutes predicted outcomes for observed Y. Default FALSE.
#' @param crossfit_folds Integer >= 2 for K-fold cross-fitting of the outcome model, or NULL (default) to fit on the full data. Only used when \code{outcome_model = TRUE}.
#'
#' @return An S3 object of class \code{causal_estimates} with the following
#'   components:
#' \describe{
#'   \item{percentESS}{Percentage sample ESS of the pseudo-population.}
#'   \item{moments.ar}{Array of dimension \eqn{3 \times K \times L}: estimated
#'     means, SDs, and medians (dim 1) for \eqn{K} groups (dim 2) and \eqn{L}
#'     outcomes (dim 3).}
#'   \item{otherFeatures.v}{Estimated mean group differences for \eqn{L}
#'     outcomes.}
#'   \item{collatedMoments.ar}{Array of dimension \eqn{3 \times K \times L
#'     \times B}: \code{moments.ar} for each of \eqn{B} bootstrap samples
#'     (only present when \code{B > 0}).}
#'   \item{collatedOtherFeatures.mt}{Matrix of dimension \eqn{L \times B}:
#'     \code{otherFeatures.v} for each of \eqn{B} bootstrap samples (only
#'     present when \code{B > 0}).}
#'   \item{collatedESS}{Vector of length \eqn{B}: percentage sample ESS for
#'     each bootstrap sample (only present when \code{B > 0}).}
#'   \item{method}{Weighting method used (\code{FLEXOR}, \code{IC}, or
#'     \code{IGO}).}
#'   \item{selected_nodesize}{Selected \code{min.node.size} for the propensity
#'     forest.}
#'   \item{diagnostics}{A list of propensity model diagnostics:
#'   \itemize{
#'     \item \code{frac_truncated}: Fraction of subjects with own-cell propensity
#'       below the truncation floor prior to stabilization.
#'     \item \code{crossfit_accuracy}: Out-of-fold classification accuracy of
#'       the propensity model.
#'     \item \code{max_weight}: Maximum weight prior to normalization.
#'     \item \code{prob_quantiles}: Quantiles of the subject-level propensity
#'       distribution.
#'   }}
#' }
#'
#' @examples
#' \donttest{
#' data(demo)
#'
#' # Point estimates only (no CIs)
#' result <- causal.estimate(S, Z, X, Y, B = 0, method = "IC", naturalGroupProp)
#' summary(result)
#'
#' # Bootstrap CIs
#' set.seed(1)
#' result <- causal.estimate(S, Z, X, Y, B = 100, method = "IC", naturalGroupProp)
#' summary(result)
#' plot(result)
#'
#' # FLEXOR method
#' result <- causal.estimate(S, Z, X, Y, B = 100, method = "FLEXOR", naturalGroupProp,
#'                            num.random = 40, seed = 1)
#'
#' # Outcome model: substitute RF predictions for observed Y
#' result <- causal.estimate(S, Z, X, Y, B = 0, method = "FLEXOR", naturalGroupProp,
#'                            outcome_model = TRUE)
#'
#' # Parallel bootstrap
#' result <- causal.estimate(S, Z, X, Y, B = 100, method = "FLEXOR", naturalGroupProp,
#'                            parallel = TRUE, n_cores = 2)
#' }
#'
#' @export
causal.estimate <- function(S, Z, X, Y, B = 0, method, naturalGroupProp = NULL, num.random = 40, gammaMin = 1e-3, gammaMax = (1-1e-3), seed = NULL, verbose = TRUE, parallel = FALSE, n_cores = NULL, outcome_model = FALSE, crossfit_folds = NULL) {

  # ensure Y is a matrix
  Y <- matrix(Y, nrow = nrow(Y))

  # validate B
  if (!is.numeric(B) || B < 0 || B != as.integer(B)) {
    stop("B must be a non-negative integer", call. = FALSE)
  }

  # validate outcome_model
  if (!is.logical(outcome_model) || length(outcome_model) != 1) {
    stop("outcome_model must be TRUE or FALSE", call. = FALSE)
  }

  # stage 1: calculate balancing weights
  weights <- balancing.weights(S, Z, X, method, naturalGroupProp, num.random, gammaMin, gammaMax, seed, verbose)

  # create structured data list with outcomes
  data <- fn.createListData(S, Z, X, Y)

  # validate outcome dimensions
  fn.userInputChecks_3(data)

  # fit outcome model if requested
  Y_hat <- if (outcome_model) {
    fn.fit_outcome_model(data, crossfit_folds = crossfit_folds)
  } else {
    NULL
  }

  # stage 2: calculate weighted moments and group differences
  c(moments.ar, otherFeatures.v) %<-% fn.Stage2(
    local_data = data,
    local_wt.v = weights$wt.v,
    Y_hat = Y_hat,
    outcome_model = outcome_model
  )

  # initialize output object
  output <- list()

  # bootstrap for confidence intervals (if B > 0)
  if (B > 0) {

    c(collatedMoments.ar, collatedOtherFeatures.mt, collatedESS) %<-% bootStrap(
      data,
      moments.ar,
      moreFeatures.v = otherFeatures.v,
      B,
      method = method,
      method_wt.v = weights$wt.v,
      naturalGroupProp,
      num.random.b = num.random,
      gammaMin,
      gammaMax,
      seed,
      verbose,
      parallel = parallel,
      n_cores = n_cores,
      outcome_model = outcome_model,
      crossfit_folds = crossfit_folds,
      nodesize = weights$selected_nodesize
    )

    # store bootstrap results
    output$collatedMoments.ar <- collatedMoments.ar
    output$collatedOtherFeatures.mt <- collatedOtherFeatures.mt
    output$collatedESS <- collatedESS
  }

  # store point estimates and metadata
  output$percentESS <- weights$percentESS
  output$moments.ar <- moments.ar
  output$otherFeatures.v <- otherFeatures.v
  output$method <- method
  output$selected_nodesize <- weights$selected_nodesize
  output$diagnostics <- weights$diagnostics

  # set class for output
  class(output) <- "causal_estimates"
  output
}

Try the WMAP package in your browser

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

WMAP documentation built on Oct. 6, 2026, 1:07 a.m.