R/utils_pairs.R

Defines functions .safe_max .check_fixed_group .decision_matrix .lagged_pairs

# ============================================================
# utils_pairs.R - linking decisions across occasions
# ============================================================

# Pairs each decision with the decision that precedes it.
#
# lag = "scheduled": the previous decision is the one recorded at the
#   immediately preceding scheduled occasion (integer time index t - 1).
#   Both decisions must be non-missing. A unit that misses occasion t - 1
#   contributes no transition at t. This matches the definition
#   p_ab(t) = Pr(D_t = b | D_{t-1} = a).
#
# lag = "recorded": the previous decision is the one in the unit's previous
#   data row, whatever its occasion. This reproduces AIBias 0.1.1.
#
# Returns a tibble with the id, group and time columns of the object plus
# `D_lag` (previous decision) and `T_curr` (current integer occasion).
.lagged_pairs <- function(object, lag = c("scheduled", "recorded")) {
  lag      <- match.arg(lag)
  data     <- object$data
  id_col   <- object$meta$id
  time_col <- object$meta$time_int
  dec_col  <- object$meta$decision

  if (lag == "recorded") {
    out <- data |>
      arrange(.data[[id_col]], .data[[time_col]]) |>
      group_by(.data[[id_col]]) |>
      mutate(
        D_lag  = dplyr::lag(.data[[dec_col]]),
        T_curr = .data[[time_col]]
      ) |>
      ungroup() |>
      filter(!is.na(.data$D_lag))
    return(out)
  }

  prev <- data[!is.na(data[[dec_col]]), c(id_col, time_col, dec_col)]
  names(prev) <- c(".id", ".t_prev", "D_lag")
  prev$.t_next <- prev$.t_prev + 1L
  prev$.t_prev <- NULL

  curr <- data[!is.na(data[[dec_col]]), , drop = FALSE]
  curr$.id     <- curr[[id_col]]
  curr$.t_next <- curr[[time_col]]

  out <- dplyr::inner_join(curr, prev, by = c(".id", ".t_next"))
  out$T_curr <- out[[time_col]]
  out$.id    <- NULL
  out$.t_next <- NULL
  out |> arrange(.data[[id_col]], .data[[time_col]])
}


# Unit-by-occasion layout of the panel.
#
# Returns a list with
#   Y : integer matrix (units x occasions); the decision, NA when the unit has
#       no recorded decision at that occasion
#   R : logical matrix; TRUE when the unit has a data row at that occasion
#       (rows with a missing decision count as present but unscored)
#   G : character vector of group labels, one per unit
.decision_matrix <- function(object) {
  data     <- object$data
  id_col   <- object$meta$id
  time_col <- object$meta$time_int
  grp_col  <- object$meta$group
  dec_col  <- object$meta$decision

  ids <- unique(data[[id_col]])
  nT  <- object$meta$n_times
  ii  <- match(data[[id_col]], ids)
  tt  <- data[[time_col]]

  Y <- matrix(NA_integer_, nrow = length(ids), ncol = nT)
  R <- matrix(FALSE,       nrow = length(ids), ncol = nT)
  Y[cbind(ii, tt)] <- data[[dec_col]]
  R[cbind(ii, tt)] <- TRUE

  G <- as.character(data[[grp_col]])[!duplicated(ii)]
  G <- G[order(ii[!duplicated(ii)])]

  list(Y = Y, R = R, G = G, ids = ids)
}


# Decomposition and bootstrap follow units over time and need one group per
# unit; trajectory and transition summaries do not.
.check_fixed_group <- function(object, fun) {
  varies <- object$meta$group_varies
  if (is.null(varies)) {
    d <- object$data
    varies <- any(tapply(as.integer(d[[object$meta$group]]), as.character(d[[object$meta$id]]),
                         function(x) length(unique(x))) > 1)
  }
  if (isTRUE(varies)) {
    abort(c(paste0("`", fun, "` needs each unit to stay in one group."),
            "x" = paste0("Some units change `", object$meta$group, "` over time."),
            "i" = "Fix the group per unit (for example, its first recorded value) and rebuild."))
  }
  invisible(TRUE)
}

.safe_max <- function(x) {
  x <- x[!is.na(x)]
  if (length(x) == 0) NA_real_ else max(x)
}

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.