liveBook · Manning

Kmeans() function

As explained in Statistics Slam Dunk

The kmeans() function is a base R function that fits a K-means clustering model to numeric data.

The base R kmeans() function groups numeric observations into a chosen number of clusters. In an NBA example, it groups 30 teams using total payroll and regular-season wins. section 11.5.2

Choose K from cluster-count diagnostics, then provide the data and desired cluster count. Optional iter.max controls algorithm iterations, while nstart repeats random initialization to improve the chance of finding a better configuration. section 11.5.2

Four NBA clusters

k <- kmeans(final_kmeans, 4, iter.max = 25, nstart = 25) print(k) The result reports cluster sizes, cluster means, team assignments, within-cluster sums of squares, and the proportion of variation explained between clusters. Here, four clusters contain 15, 1, 3, and 11 teams, with 91.6% of total variation between clusters. section 11.5.2

k <- kmeans(final_kmeans, 4, iter.max = 25, nstart = 25) 
print(k)
## K-means clustering with 4 clusters of sizes 15, 1, 3, 11
##
## Cluster means:
##   salarytotal wintotal
## 1  1366605768 700.8667
## 2  2034231301 626.0000
## 3  1763863525 835.0000
## 4  1490569128 746.0000
##
## Clustering vector:
## CHA NOP ATL BOS BKN CHI CLE DAL DEN DET GSW HOU IND LAC LAL MEM MIA MIL 
##   1   1   1   4   4   1   4   3   1   1   1   4   4   1   3   4   4   1 
## MIN NYK OKC ORL PHI PHO POR SAC SAS TOR UTA WAS 
##   1   2   1   4   4   1   3   1   4   1   1   4 
##
## Within cluster sum of squares by cluster:
## [1] 3.519544e+16 0.000000e+00 1.012325e+16 2.254863e+16
## (between_SS / total_SS =  91.6 %)
##
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"    
## [5] "tot.withinss" "betweenss"    "size"         "iter"        
## [9] "ifault"

Inspect the complete kmeans() call and its cluster assignments, centers, diagnostics, and available result components. section 11.5.2

How Statistics Slam Dunk covers it

How deep it goes
Explains required and optional arguments, iterative optimization, initialization, and returned diagnostics, but not algorithm internals beyond centroids and sums of squares.
Examples
Uses NBA payrolls, regular-season wins, four clusters, printed diagnostics, and a cluster visualization.
What it assumes
Assumes numeric clustering variables and a selected cluster count, while demonstrating how to compare candidate counts before fitting.
What you can do after
Apply it via base R to construct clusters and inspect assignments, centers, sizes, and variation diagnostics.
How it connects
Connects K-means clustering with centroids, within-cluster sum of squares, silhouette analysis, and scree plots.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Statistics Slam Dunk. The section links point to the parts of the book it draws on.