R/poisson_scale.R

Defines functions poisson_scale

Documented in poisson_scale

#' @title Poisson Scaling
#'
#' @author Christian L. Goueguel
#'
#' @description
#' This function performs Poisson scaling on a numeric matrix or data frame.
#' Poisson scaling scales each variable by its square root mean value,
#' with an optional scaling offset to avoid over-scaling when a variable has a
#' near-zero mean.
#'
#' @param x A numeric matrix or data frame.
#' @param sc A vector of previously calculated scales. If provided, these scales
#' will be applied to the data.
#' @param drop_na A logical value indicating whether to remove rows containing
#' missing values. If `TRUE` (the default), such rows are removed. If `FALSE`,
#' missing values are kept and ignored when computing the means.
#' @param options A list of options for Poisson scaling. See the 'Options' section below.
#' @param drop.na `r lifecycle::badge("deprecated")` Use `drop_na`.
#'
#' @return If `sc` is not provided, the function returns a list with the following components:
#'   \item{`xs`}{The Poisson-scaled data.}
#'   \item{`sc`}{A vector of scales calculated for the given data.}
#'
#'   If `sc` is provided, the function returns the Poisson-scaled data `xs`.
#'
#' @section Options:
#' The `options` argument is a list with the following fields:
#'   \itemize{
#'     \item `offset`: A numeric value representing the percentage of the maximum mean value to be used as an offset on all scales. Avoids division by near-zero means. Default is 3.
#'     \item `mode`: An integer value (1 or 2) specifying the dimension of the data on which to calculate the mean value for scaling. 1 = mean over rows (to scale variables); 2 = mean over columns (to scale samples). Default is 1.
#'   }
#'
#' @export poisson_scale
#'
#' @examples
#' data(forageLIBS)
#' spectra <- forageLIBS[-(1:14)]  # the spectral channels
#' res <- poisson_scale(spectra[1:300, ])
#' head(res$sc)
#' # the same scales for new spectra
#' poisson_scale(spectra[301:368, ], sc = res$sc)[1:3, 1:4]
poisson_scale <- function(x, sc = NULL, drop_na = TRUE, options = list(),
                          drop.na = deprecated()) {
  drop_na <- renamed_arg(drop.na, drop_na, "poisson_scale", "drop.na", "drop_na")

  if (missing(x)) {
    stop("Missing 'x' argument.")
  }
  if (!is.numeric(x) && !is.data.frame(x) && !tibble::is_tibble(x)) {
    stop("'x' must be a numeric matrix or data frame.")
  }

  if (!is.logical(drop_na)) {
    stop("'drop_na' must be a logical value (TRUE or FALSE).")
  }
  x <- as_numeric_matrix(x, "x")

  # Set default options
  default_options <- list(offset = 3, mode = 1)
  options <- utils::modifyList(default_options, options)
  if (!options$mode %in% c(1, 2)) {
    stop("Invalid 'mode' value. It must be either 1 or 2.")
  }

  if (!is.null(sc)) {
    n_sc <- if (options$mode == 1) ncol(x) else nrow(x)
    if (!is.numeric(sc) || length(sc) != n_sc) {
      stop("'sc' must be a numeric vector with one scale per ",
           if (options$mode == 1) "column" else "row", " of 'x'.")
    }
    # Apply previously calculated scales
    return(sweep(x, if (options$mode == 1) 2 else 1, sc, "/"))
  }

  if (drop_na) {
    x <- x[stats::complete.cases(x), , drop = FALSE]
  }

  # Calculate mean values
  if (options$mode == 1) {
    means <- colMeans(x, na.rm = TRUE)
  } else if (options$mode == 2) {
    means <- rowMeans(x, na.rm = TRUE)
  } else {
    stop("Invalid 'mode' value. It must be either 1 or 2.")
  }

  # Calculate scaling offset
  max_mean <- max(means, na.rm = TRUE)
  offset <- max_mean * (options$offset / 100)

  # Calculate scales
  sc <- sqrt(means + offset)

  # Check for zero scales
  if (any(sc == 0)) {
    warning("Some variables have zero scale and will not be scaled.")
    sc[sc == 0] <- 1  # Set zero scales to 1 to avoid division by zero
  }

  # Perform Poisson scaling
  xs <- sweep(x, if (options$mode == 1) 2 else 1, sc, "/")

  return(list(xs = xs, sc = sc))
}

Try the specProc package in your browser

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

specProc documentation built on Nov. 20, 2026, 5:11 p.m.