Skip to contents

Perform k-means clustering on the matrix, adding cluster assignments to metadata and optionally storing the full kmeans object.

Usage

compute_kmeans(x, centers, name = NULL, store = TRUE, ...)

Arguments

x

A tidymatrix object

centers

Number of clusters (k) or a set of initial cluster centers.

name

Name for this analysis. Default is "row_kmeans" or "column_kmeans" depending on active component.

store

If TRUE, stores the full kmeans object for later retrieval with get_analysis(). Default is TRUE.

...

Additional arguments passed to stats::kmeans(), such as iter.max, nstart, algorithm, etc.

Value

A tidymatrix object with cluster assignments added to metadata

Details

This function wraps stats::kmeans(), passing additional parameters directly to it.

Examples

mat <- matrix(rnorm(100), nrow = 10, ncol = 10)
row_data <- data.frame(id = 1:10)
tm <- tidymatrix(mat, row_data)

# K-means clustering with k=3
tm <- tm |>
  activate(rows) |>
  compute_kmeans(centers = 3, nstart = 25)

# Now row_data has row_kmeans_cluster column

# Get full kmeans object
km <- get_analysis(tm, "row_kmeans")
km$tot.withinss  # Total within-cluster sum of squares
#> [1] 42.62775