R/utils.R

Defines functions calc_silhouette_score calc_ari parse_verbosity

Documented in calc_ari calc_silhouette_score parse_verbosity

# metrics ----------------------------------------------------------------------

## others ----------------------------------------------------------------------

#' Helper to parse verbosity
#'
#' @param x Boolean or integer to parse
#'
#' @returns The integer value controlling the verbosity
#'
#' @keywords internal
parse_verbosity <- function(x) {
  # checks
  checkmate::qassert(x, c("B1", "I1[0,2]"))

  as.integer(sum(x))
}

## cluster metrics -------------------------------------------------------------

#' Adjusted Rand index calculation
#'
#' @description
#' Calculates the adjusted Rand index between two sets of cluster assignments.
#'
#' @param members_a Integer vector. Membership/assignment of the first
#' clustering algorithm.
#' @param members_b Integer vector. Membership/assignment of the second
#' clustering algorithm.
#'
#' @returns Adjusted Rand index
#'
#' @examples
#' d <- manifold_synthetic_data(type = "clusters", n_samples = 500L)
#' km <- kmeans_cluster(d$data, k = 4L, .verbose = FALSE)
#' calc_ari(membership(km), d$membership)
#'
#' @export
calc_ari <- function(members_a, members_b) {
  # checks
  checkmate::qassert(members_a, "I+")
  checkmate::qassert(members_b, "I+")
  checkmate::assertTRUE(length(members_a) == length(members_b))

  rs_ari(cluster_membership_a = members_a, cluster_membership_b = members_b)
}

#' Calculates the Silhouette score of a given clustering
#'
#' @description
#' If the membership has only one group, the function will return `NaN` for
#' `mean_silhouette` and `silhouette_scores`.
#'
#' @param data Numerical matrix. Samples x features. The matrix that was used
#' to generate the clustering.
#' @param membership Integer vector. Membership/assignment of the clustering
#' algorithm.
#'
#' @returns A list with the following items:
#' \itemize{
#'  \item mean_silhouette - The average Silhouette scores across all the data
#'  points.
#'  \item silhouette_scores - The individual Silhouette scores of all the data
#'  points.
#' }
#'
#' @examples
#' d <- manifold_synthetic_data(type = "clusters", n_samples = 500L)
#' km <- kmeans_cluster(d$data, k = 4L, .verbose = FALSE)
#' res <- calc_silhouette_score(d$data, membership(km))
#' res$mean_silhouette
#'
#' @export
calc_silhouette_score <- function(data, membership) {
  # checks
  checkmate::assertMatrix(data, mode = "numeric", nrows = length(membership))
  checkmate::qassert(membership, "I+")

  res <- rs_silhouette_score(data = data, cluster_membership = membership)

  res
}

Try the manifoldsR package in your browser

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

manifoldsR documentation built on Nov. 17, 2026, 5:09 p.m.