Computational Provenance & Reproducibility Record

RAISINS - R and AI Solutions for INferential Statistics · Online Statistical Analysis Platform for Agricultural Research

Computational Provenance & Reproducibility Record K-MEANS CLUSTER ANALYSIS · 2.0.0 · DOI 10.5281/zenodo.21486504

Computational Provenance & Reproducibility Record

RAISINS · K-Means Cluster Analysis Module

This Computational Provenance Record documents the statistical computing environment, software dependencies, computational provenance, and bibliographic references associated with the RAISINS K-Means Cluster Analysis module. It is intended to support computational reproducibility and software transparency. Detailed statistical methodology, mathematical derivations, and user guidance are provided separately in the official module documentation.

Any issues or updates required please comment here

Go to the App from here

1 Module Metadata

Parameter Specification
Module K-Means Cluster Analysis
Module Version 2.0.0
DOI 10.5281/zenodo.21486504
Document Type Computational workflow
Statistical Engine R
R Version 4.5.2
Reproducibility Execution Environment: Posit Connect · GCR · renv-locked

2 Statistical Dependency Manifest

Package Version Repository Core Statistical Functions
stats 4.5.2 Base R kmeans(), prcomp(), dist()
factoextra 1.0.7 CRAN fviz_nbclust(), get_dist()
cluster 2.1.8.1 CRAN clusGap(), maxSE()
clValid 0.7 CRAN clValid()

3 Statistical Function Registry

Analytical Role Primary Function(s)
Variable scaling base::scale() and internal min-max / unit-length / robust routines
Clustering stats::kmeans()
Optimal cluster number factoextra::fviz_nbclust() (elbow, silhouette), cluster::clusGap() (gap statistic)
Dimensionality reduction stats::prcomp()
Distance / dissimilarity factoextra::get_dist()
Internal cluster validation clValid::clValid()

4 Default Methods & Parameters

Analysis Step / Parameter Default Method / Value
Variable
Scaling
Default method Z-score standardisation (mean 0, SD 1) applied to every selected clustering variable before analysis
Alternatives Centering only, min-max (0-1), unit-length, robust (median / IQR), or none, selectable per run
Rationale K-Means uses Euclidean distance, which is dominated by variables with the largest numeric range; scaling puts all clustering variables on a comparable footing
K-Means
Clustering

(kmeans())
Algorithm Hartigan-Wong (R's kmeans() default)
Restarts nstart = 20, best solution (lowest total within-cluster sum of squares) retained across restarts to reduce sensitivity to initial centroid placement
Iterations iter.max = 50
Number of clusters (k) User-specified; pre-filled automatically from the elbow-method suggestion (see below). Must satisfy 2 ≤ k < n
Optimal k Elbow method factoextra::fviz_nbclust(..., method = "wss"); suggested k is taken at the point of maximum decrease in the rate of within-cluster sum-of-squares reduction
Silhouette method factoextra::fviz_nbclust(..., method = "silhouette"); suggested k maximises the average silhouette width
Gap statistic cluster::clusGap() with cluster::maxSE(..., method = "firstSEmax"); suggested k is the smallest k within one standard error of the maximum gap
Distance /
Dissimilarity
Metric Euclidean distance on the scaled data, computed via factoextra::get_dist()
Reported as Pairwise Euclidean distance matrix between observations (Metrics tab)
Internal
Validation

(clValid())
Range evaluated k = 2 to 6, method "kmeans", validation "internal"
Measures reported Connectivity (lower is better), Dunn Index (higher is better), Silhouette Width (higher is better); the best k under each measure is reported independently, measures may disagree
Dimensionality
Reduction

(prcomp())
Principal Component Analysis Computed on the scaled data (scale. = FALSE, data already scaled upstream); percentage of variance explained by PC1 and PC2 is reported

5 R Code for Key Analytical Steps

The code blocks below demonstrate the exact computation used to obtain every result reported by the RAISINS K-Means Cluster Analysis module, using the USArrests dataset (Murder, Assault, UrbanPop, Rape; 50 U.S. states) built into the datasets package.

5.1 Scaling and K-Means Clustering

data(USArrests)
X  <- USArrests                      # Murder, Assault, UrbanPop, Rape (all numeric)
Xs <- scale(X)                       # z-score standardisation (RAISINS default)

set.seed(123)
km <- kmeans(Xs, centers = 2, iter.max = 50, nstart = 20)

km$centers                           # cluster centroids (scaled units)
km$cluster                           # cluster membership of each observation
km$totss                             # total sum of squares (TSS)
km$tot.withinss                      # total within-cluster sum of squares (TWSS)
km$betweenss                         # between-cluster sum of squares (BSS)
100 * km$betweenss / km$totss        # explained variance (%)
km$withinss                          # within-cluster sum of squares, per cluster
km$size                              # number of observations, per cluster

means_by_cluster <- aggregate(X, by = list(cluster = km$cluster), mean)  # raw (unscaled) cluster means of variables
dd <- cbind(X, cluster = km$cluster)                                     # cluster membership with variables and observations

5.2 Choosing the Number of Clusters (k)

library(factoextra)
library(cluster)
library(ggplot2)

#Elbow method - WCSS by k
elbow <- fviz_nbclust(Xs, FUNcluster = kmeans, method = "wss")
wss   <- elbow$data$y
suggested_k_elbow <- which.min(diff(wss)) + 1

elbow +
  geom_vline(xintercept = suggested_k_elbow, linetype = "dashed", color = "skyblue", linewidth = 0.8) +
  theme_minimal() +
  labs(title = "Elbow Method")

#Silhouette method - average silhouette width by k
sil <- fviz_nbclust(Xs, FUN = kmeans, method = "silhouette",
                     iter.max = 50, nstart = 20)
suggested_k_silhouette <- sil$data$clusters[which.max(sil$data$y)]

sil +
  ggtitle("Average Silhouette Method") +
  theme(plot.title = element_text(hjust = 0.5))

#Gap statistic
gap <- clusGap(Xs, FUN = kmeans, nstart = 20, K.max = 10, B = 50)
suggested_k_gap <- maxSE(gap$Tab[, "gap"], gap$Tab[, "SE.sim"], method = "firstSEmax")

fviz_gap_stat(gap) +
  ggtitle("Gap Statistic Method") +
  theme(plot.title = element_text(hjust = 0.5))

5.3 Distance and Internal Validation

library(factoextra)
library(clValid)

distance   <- get_dist(Xs, method = "euclidean")   # pairwise Euclidean distance matrix
pca        <- prcomp(Xs, scale. = FALSE)           # principal component analysis
validation <- clValid(Xs, nClust = 2:6, clMethods = "kmeans", validation = "internal")

as.matrix(distance)                  # full pairwise distance matrix
validation@measures[, , 1]           # Connectivity, Dunn Index, Silhouette Width by k

# best k under each internal validation measure
val_df <- as.data.frame(validation@measures[, , 1])
opt_scores <- data.frame(
  Measure  = rownames(val_df),
  Score    = c(min(val_df["Connectivity", ]), max(val_df["Dunn", ]), max(val_df["Silhouette", ])),
  Clusters = c(
    as.numeric(colnames(val_df)[which.min(val_df["Connectivity", ])]),
    as.numeric(colnames(val_df)[which.max(val_df["Dunn", ])]),
    as.numeric(colnames(val_df)[which.max(val_df["Silhouette", ])])
  )
)

Explore the entire K-Means Cluster Analysis module in preview mode using our demo datasets. To submit suggestions or report a workflow issue, please use the discussion section below, or visit the official RAISINS website.

6 RAISINS Native Statistical Framework

RAISINS uses R for all its statistical computations. Every package used to generate major results is listed and demonstrated with examples, so results can be reproduced independently. These results are then organized and formatted on the RAISINS website along with visualisation to make them easier to use and interpret. RAISINS also has its own custom-built statistical tools for managing workflows, validating results, and generating reports. Details of these are not fully covered here, they’re shared with outside researchers only on request, and are subject to licensing terms.

7 Package References

R Core Team. (2025). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. https://www.R-project.org/

Kassambara, A., & Mundt, F. (2020). factoextra: Extract and Visualize the Results of Multivariate Data Analyses (R package version 1.0.7). https://doi.org/10.32614/CRAN.package.factoextra

Maechler, M., Rousseeuw, P., Struyf, A., Hubert, M., & Hornik, K. (2025). cluster: “Finding Groups in Data”: Cluster Analysis Extended Rousseeuw et al. (R package version 2.1.8.1). https://doi.org/10.32614/CRAN.package.cluster

Brock, G., Pihur, V., Datta, S., & Datta, S. (2021). clValid: Validation of Clustering Results (R package version 0.7). https://doi.org/10.32614/CRAN.package.clValid

Allaire, J. J., Xie, Y., Dervieux, C., McPherson, J., Luraschi, J., Ushey, K., Atkins, A., Wickham, H., Cheng, J., Chang, W., & Iannone, R. (2026). rmarkdown: Dynamic Documents for R (R package version 2.31). https://github.com/rstudio/rmarkdown

Feedback & Discussion