R/average.R

Defines functions average

Documented in average

#' @title Fast Average for Large Spectral Dataset
#'
#' @author Christian L. Goueguel
#'
#' @description
#' This function efficiently averages the samples spectra in a large
#' dataset. It provides flexibility by computing either the overall
#' mean across all spectra or group-wise means based on the values of a
#' specified grouping column.
#'
#' @details
#' The function leverages the power of `Rcpp` to perform the mean calculations
#' in C++. The underlying C++ implementation has a time complexity of
#' \emph{O(n x m)}, where \emph{n} is the number of rows and \emph{m} is
#' the number of columns in the data. Missing values are ignored in the
#' computation of each mean.
#'
#' @param x A data frame or tibble.
#' @param group_by The column to group the data by (optional), given either
#'   unquoted or as a string. If not provided, the average of the overall data
#'   will be computed.
#' @param .group_by `r lifecycle::badge("deprecated")` Use `group_by`.
#' @return
#'   - If `group_by = NULL`, a one-row tibble containing the mean of each column.
#'   - If `group_by` is provided, a tibble with one row per group: the first
#'   column holds the group labels and the remaining columns hold the group means.
#'
#' @export average
#'
#' @examples
#' data(forageLIBS)
#' # one mean spectrum per sample: three samples were measured twice
#' means <- average(forageLIBS[-c(1, 3:14)], Sample)
#' dim(means)
average <- function(x, group_by = NULL, .group_by = deprecated()) {
  if (missing(x)) {
    stop("Missing 'x' argument.")
  }
  if (!is.data.frame(x)) {
    stop("'x' must be a data frame or tibble.")
  }

  # Quoted, since the column may be given unquoted.
  group_quo <- renamed_arg(if (missing(.group_by)) deprecated() else rlang::enquo(.group_by),
                           rlang::enquo(group_by), "average", ".group_by", "group_by")

  if (rlang::quo_is_null(group_quo)) {
    Xmat <- as_numeric_matrix(x, "x")
    avg <- computeMeans(Xmat)
    return(as_tbl(avg, names(x)))
  }

  group_name <- rlang::as_name(group_quo)
  if (!group_name %in% colnames(x)) {
    stop("Grouping variable 'group_by' not found in the data")
  }

  data_cols <- setdiff(names(x), group_name)
  Xmat <- as_numeric_matrix(x[data_cols], "x")
  grp <- x[[group_name]]
  if (!is.factor(grp)) {
    grp <- factor(grp, levels = unique(grp[!is.na(grp)]))
  }

  avg <- computeGroupedMeans(Xmat, as.integer(grp), nlevels(grp))
  out <- as_tbl(avg, data_cols)
  out <- tibble::add_column(out, !!group_name := levels(grp), .before = 1)
  return(out)
}

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.