Skip to main content

Clustering

Week 8. Last week PCA squeezed many correlated variables into a few axes. This week we ask a different question of the same kind of data: are there groups? Nobody gives us labels; the algorithm has to find them. Monday is k-means: pick k centres, assign every point to the nearest one, move each centre to the mean of its points, repeat. Wednesday is hierarchical clustering: build the whole tree of who is closest to whom, then cut it wherever you like. Both depend on what “close” means, so scaling and the choice of distance matter as much as the method.

Problem Set 8: Clustering — due Monday, November 23, 1:10 PM. Submit on Canvas.

Answer key: Problem Set 8 key

Data: colombia_climate.csv (the 19 WorldClim bioclimatic variables for 3571 grid cells covering Colombia, about 18 km on a side), a_thaliana_150_snps.csv (150 Arabidopsis thaliana plants scored at 10,933 genetic markers, with country and coordinates), gene_expression.csv (1000 Arabidopsis genes across 53 tissues and stages), and for Problem Set 8: winedata.csv (the Week 1 and PS7 wine data)


Monday — K-means

Why cluster; the algorithm step by step (random centres, join the nearest, move to the mean, repeat until nothing changes); many random starts and nstart; distance and why we scale; choosing k with the elbow and the silhouette; and k-means always finds k clusters, real or not. Case study: climate types of Colombia.

Wednesday — Hierarchical clustering

Trees and how to read them (height = distance at the merge); building one by hand from a distance matrix; cutree(); linkage (complete, single, average, Ward); choosing a distance (Euclidean, Manhattan, 1 − correlation, binary); real data: Arabidopsis population structure and a gene expression heatmap; k-means or hierarchical, and methods for odd shapes.

Friday — Publication-ready figures

Step-by-step tutorial → (journal sizes, a clean theme, colour-blind-safe colours, plotting the model with its CI, points instead of bar plots, multi-panel figures with patchwork, saving PDF and PNG)

Also available: parallel computing and big data in R

Step-by-step tutorial → (timing code, vectorizing, running many k-means fits in parallel, reading big files fast)

Key Packages

library(ggplot2)
library(cluster)    # silhouette()
library(patchwork)  # side-by-side plots

Earlier versions