An R package implementing batch and streaming k-means clustering with core computations written in C via the R native API.
Overview
stReans provides two complementary approaches to k-means clustering:
-
kmeans_batch()- Lloyd’s algorithm for datasets that fit in memory, with convergence detection based on centroid shift -
kmeans_stream_new()- incremental online k-means for data streams, processing one observation at a time without storing the full dataset
Installation
The package is not on CRAN. Install directly from GitHub:
# install.packages("devtools")
devtools::install_github("Luki308/stReans")Usage
Batch K-Means
library(stReans)
# generate three well-separated clusters
set.seed(42)
cluster1 <- matrix(rnorm(40, mean = 0, sd = 0.5), nrow = 20)
cluster2 <- matrix(rnorm(40, mean = 5, sd = 0.5), nrow = 20)
cluster3 <- matrix(rnorm(40, mean = 10, sd = 0.5), nrow = 20)
X <- rbind(cluster1, cluster2, cluster3)
# run batch k-means
result <- kmeans_batch(X, k = 3L, max_iter = 100L, tol = 1e-6)
result$centers # cluster centroids
result$assignments # cluster label per observation
result$iterations # how many iterations ranTesting
Unit tests are written with testthat and run automatically via GitHub Actions on Linux, macOS, and Windows:
-
tests/testthat/test-batch.R- correctness, edge cases, input validation -
tests/testthat/test-utils.R- distance and layout conversion utilities