R/ClusterSilhouette.R

Defines functions ClusterSilhouette

Documented in ClusterSilhouette

ClusterSilhouette = function(Cls, DataOrDistances, DistanceMethod = "euclidean",
                             Silent = TRUE, ...) {
  # V=ClusterSilhouette(Cls,Data)
  #
  # Mean Silhouette Width [Rousseeuw, 1987]
  #
  # INPUT
  # Cls[1:n]                 Numeric, character or factor cluster labels; no missing labels
  # DataOrDistances          Data[1:n,1:d], dissimilarities[1:n,1:n] or a dist object
  #
  # OPTIONAL
  # DistanceMethod           Distance method; default "euclidean"; ignored for distances
  # Silent                   TRUE suppresses distance progress, not warnings/messages
  # ...                      Further arguments for parallelDist::parDist()
  #                          or stats::dist() if parallelDist is unavailable
  #
  # OUTPUT
  # List V with
  #   Silhouette               Mean silhouette width; larger values are better
  #   Object                   cluster::silhouette object; ClusterLabels attribute maps labels
  #
  # DETAILS
  # Labels, including zero, are ordinary clusters. Singleton widths
  # are zero. Fewer than 2 or more than n-1 clusters yield NaN.
  # A missing optional cluster package yields NaN and a reason in Object.
  #
  # Author: Michael Thrun, 11/2026
  #
  # [Rousseeuw, 1987] Rousseeuw, P. J.: Silhouettes: A graphical aid to the interpretation and validation of cluster analysis, Journal of Computational and Applied Mathematics, Vol. 20, pp. 53-65, DOI:10.1016/0377-0427(87)90125-7, 1987.
  #
  Input = internalClusterValidation(Cls, DataOrDistances, "ClusterSilhouette",
                                    TRUE, DistanceMethod, Silent, ...)
  DataDists = Input$Data
  Cls = Input$Cls
  Labels = Input$Labels
  if (!requireNamespace("cluster", quietly = TRUE)) {
    Reason = "Subordinate package (cluster) is missing. Please install it from Suggests."
    message(Reason)
    return(list(Silhouette = NaN, Object = Reason))
  }
  if (length(Labels) < 2L || length(Labels) >= length(Cls)) {
    warning("ClusterSilhouette: requires between 2 and n-1 clusters")
    return(list(Silhouette = NaN, Object = NULL))
  }
  Object = cluster::silhouette(Cls, stats::as.dist(DataDists))
  attr(Object, "ClusterLabels") = Labels
  return(list(Silhouette = mean(Object[, "sil_width"]), Object = Object))
}

Try the FCPS package in your browser

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

FCPS documentation built on Nov. 28, 2026, 9:08 a.m.