R/memory_undersampling.R

Defines functions memory_balance.memory_undersampling memory_undersampling

Documented in memory_undersampling

#' @title Memory with undersampling
#' @description The training data keeps every row of the minority class and the same number of
#'  rows of the majority class, drawn at random (kept in temporal order).
#' @param min_per_class Minimum number of rows of each class to balance. Below it, the training
#'  data is the observed (unbalanced) data.
#' @return A `memory_undersampling` object.
#' @export
memory_undersampling <- function(min_per_class = 50) {
  obj <- memory_manager()
  obj$min_per_class <- min_per_class
  class(obj) <- append("memory_undersampling", class(obj))
  obj
}

#' @export
memory_balance.memory_undersampling <- function(obj, X, y) {
  idx_true  <- which(y[, 1] == TRUE)
  idx_false <- which(y[, 1] == FALSE)
  if (min(length(idx_true), length(idx_false)) < obj$min_per_class) return(list(X = X, y = y))
  
  n_minor <- min(length(idx_true), length(idx_false))
  if (length(idx_true) <= length(idx_false)) {
    idx_false <- idx_false[sample.int(length(idx_false), n_minor)]
  } else {
    idx_true <- idx_true[sample.int(length(idx_true), n_minor)]
  }
  keep <- sort(c(idx_true, idx_false))
  list(X = X[keep, , drop = FALSE], y = y[keep, , drop = FALSE])
}

Try the heimdall package in your browser

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

heimdall documentation built on Dec. 2, 2026, 5:08 p.m.