R/085_atoms_stats.R

Defines functions cvxr_var cvxr_std cvxr_mean

Documented in cvxr_mean cvxr_std cvxr_var

#####
## DO NOT EDIT THIS FILE!! EDIT THE SOURCE INSTEAD: rsrc_tree/atoms/stats.R
#####

## CVXPY SOURCE: atoms/stats.py
## Statistics atoms: mean, std, var

#' Mean of an expression
#'
#' @description
#' Computes the arithmetic mean of an expression along an axis.
#'
#' @param x An Expression or numeric value.
#' @param axis NULL (all), 1 (row-wise), or 2 (column-wise).
#' @param keepdims Logical; keep reduced dimension?
#' @returns An Expression representing the mean.
#' @export
cvxr_mean <- function(x, axis = NULL, keepdims = FALSE) {
  x <- as_expr(x)
  if (is.null(axis)) {
    sum_entries(x, axis = NULL, keepdims = keepdims) / expr_size(x)
  } else {
    axis <- as.integer(axis)
    if (!axis %in% c(1L, 2L)) {
      cli_abort("{.fn cvxr_mean} only supports axis = NULL, 1, or 2.")
    }
    sum_entries(x, axis = axis, keepdims = keepdims) / x@shape[3L - axis]
  }
}

#' Standard deviation of an expression
#'
#' @description
#' Computes the standard deviation of an expression.
#'
#' @param x An Expression or numeric value.
#' @param axis NULL (all), 1 (row-wise), or 2 (column-wise).
#' @param keepdims Logical; keep reduced dimension?
#' @param ddof Degrees of freedom correction (default 0, population std).
#' @returns An Expression representing the standard deviation.
#' @export
cvxr_std <- function(x, axis = NULL, keepdims = FALSE, ddof = 0) {
  x <- as_expr(x)
  if (is.null(axis)) {
    centered <- vec(x - cvxr_mean(x))
    cvxr_norm(centered, p = 2) / sqrt(expr_size(x) - ddof)
  } else {
    axis <- as.integer(axis)
    if (!axis %in% c(1L, 2L)) {
      cli_abort("{.fn cvxr_std} only supports axis = NULL, 1, or 2.")
    }
    n <- x@shape[3L - axis]
    centered <- x - cvxr_mean(x, axis = axis, keepdims = TRUE)
    cvxr_norm(centered, p = 2, axis = axis, keepdims = keepdims) / sqrt(n - ddof)
  }
}

#' Variance of an expression
#'
#' @description
#' Computes the variance. Only supports full reduction (axis = NULL).
#'
#' @param x An Expression or numeric value.
#' @param axis NULL only (axis reduction not yet supported).
#' @param keepdims Logical; keep reduced dimension?
#' @param ddof Degrees of freedom correction (default 0, population variance).
#' @returns An Expression representing the variance.
#' @export
cvxr_var <- function(x, axis = NULL, keepdims = FALSE, ddof = 0) {
  x <- as_expr(x)
  if (!is.null(axis)) {
    cli_abort(c(
      "{.fn cvxr_var} does not yet support axis reduction.",
      "i" = "Use {.code square(cvxr_std(x, axis, keepdims, ddof))} instead."
    ))
  }
  sum_squares(x - cvxr_mean(x)) / (expr_size(x) - ddof)
}

Try the CVXR package in your browser

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

CVXR documentation built on March 6, 2026, 9:10 a.m.