R/inertia_calc.R

Defines functions inertia_calc

Documented in inertia_calc

#' Cluster Inertia Calculation
#'
#' Calculate inertia for a given subset of the distance matrix from the original
#' data set provided to `x`. Assumes that distance matrices are stored as
#' matrices and not distance objects.
#'
#' @param x Distance matrix, not an object of some distance measure.
#'
#' @return Inertia value of the matrix, formula in Chavent (1998). If `x` is a
#'   single number, return 0.
#' @export
#' @examples
#' data(iris)
#'
#' # Euclidean distance on first 20 rows of the 4 continuous variables
#' dist_mat <- as.matrix(dist(iris[1:20, 1:4]))
#' inertia_calc(dist_mat)
inertia_calc <- function(x) {

  if (!is.numeric(x) && !is.matrix(x))
    stop("\"x\" has to be a numerical value or matrix.")

  # If singleton cluster, inertia is 0
  inertia_value <- ifelse(length(x) == 1 && is.numeric(x),
                          0,
                          sum(x^2) / (dim(x)[1] * 2))
  return(inertia_value)
}
vinhtantran/monoClust documentation built on March 12, 2021, 11:11 p.m.