R/aib_simulate.R

Defines functions aib_simulate

Documented in aib_simulate

#' Simulate repeated binary decisions with selective observation
#'
#' @description
#' Generates a panel of repeated 0/1 decisions that follow a two-state
#' Markov chain within each group, and optionally hides decisions with a
#' probability that depends on the group and on the unit's previous (true)
#' decision. Useful for checking an audit against known components and for
#' teaching.
#'
#' @param n Integer. Units per group (scalar, or one value per group).
#' @param n_times Integer. Number of occasions (at least 2).
#' @param groups Character. Group labels; the first is used as the reference
#'   group in the examples.
#' @param init Numeric. Probability of a favorable first decision, one per
#'   group.
#' @param p01 Numeric. Recovery probability \eqn{Pr(D_t = 1 | D_{t-1} = 0)},
#'   one per group.
#' @param p11 Numeric. Retention probability \eqn{Pr(D_t = 1 | D_{t-1} = 1)},
#'   one per group.
#' @param observe NULL for complete observation, or a 2-row matrix of
#'   observation probabilities with one column per group: row 1 after an
#'   unfavorable previous decision, row 2 after a favorable one. The first
#'   occasion is always observed.
#' @param unobserved Character. `"na"` (default) keeps unobserved occasions
#'   as rows with a missing decision; `"drop"` removes them.
#' @param seed Integer or NULL. Random seed.
#'
#' @return A data frame with columns `id`, `time`, `group`, `decision` and
#'   `decision_true` (the decision before any hiding).
#'
#' @examples
#' # Equal recovery and retention gaps (zero amplification index),
#' # yet the approval gap widens.
#' sim <- aib_simulate(n = 2000, n_times = 4, groups = c("ref", "focal"),
#'                     init = c(0.5, 0.5), p01 = c(0.2, 0.1),
#'                     p11 = c(0.8, 0.7), seed = 1)
#' obj <- aib_build(sim, "id", "time", "group", "decision", verbose = FALSE)
#' obj <- aib_decompose(obj, ref_group = "ref")
#'
#' @export
aib_simulate <- function(n          = 500,
                         n_times    = 4,
                         groups     = c("reference", "focal"),
                         init       = c(0.5, 0.5),
                         p01        = c(0.2, 0.1),
                         p11        = c(0.8, 0.7),
                         observe    = NULL,
                         unobserved = c("na", "drop"),
                         seed       = NULL) {
  unobserved <- match.arg(unobserved)
  K <- length(groups)
  if (n_times < 2) abort("`n_times` must be at least 2.")
  rep_k <- function(x, nm) {
    if (length(x) == 1) x <- rep(x, K)
    if (length(x) != K) abort(paste0("`", nm, "` must have one value per group."))
    x
  }
  n    <- rep_k(n, "n")
  init <- rep_k(init, "init")
  p01  <- rep_k(p01, "p01")
  p11  <- rep_k(p11, "p11")
  probs <- c(init, p01, p11)
  if (any(probs < 0 | probs > 1)) abort("Probabilities must lie in [0, 1].")
  if (!is.null(observe)) {
    observe <- as.matrix(observe)
    if (!identical(dim(observe), c(2L, K)))
      abort("`observe` must be a 2 x length(groups) matrix.")
    if (any(observe < 0 | observe > 1))
      abort("`observe` probabilities must lie in [0, 1].")
  }
  if (!is.null(seed)) set.seed(seed)

  N   <- sum(n)
  gi  <- rep(seq_len(K), times = n)
  D   <- matrix(NA_integer_, N, n_times)
  O   <- matrix(TRUE, N, n_times)
  D[, 1] <- stats::rbinom(N, 1, init[gi])
  for (t in 2:n_times) {
    pr <- ifelse(D[, t - 1] == 1L, p11[gi], p01[gi])
    D[, t] <- stats::rbinom(N, 1, pr)
    if (!is.null(observe)) {
      po <- observe[cbind(D[, t - 1] + 1L, gi)]
      O[, t] <- stats::runif(N) < po
    }
  }

  out <- data.frame(
    id            = rep(seq_len(N), times = n_times),
    time          = rep(seq_len(n_times), each = N),
    group         = rep(groups[gi], times = n_times),
    decision      = as.vector(ifelse(O, D, NA_integer_)),
    decision_true = as.vector(D),
    stringsAsFactors = FALSE
  )
  out <- out[order(out$id, out$time), ]
  if (unobserved == "drop") out <- out[!is.na(out$decision), ]
  rownames(out) <- NULL
  out
}

Try the AIBias package in your browser

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

AIBias documentation built on Dec. 1, 2026, 1:06 a.m.