1 Introduction

Suppose you have measurements on a few dozen things (states, customers, genes, songs) and you want to know which ones are similar to each other. Nobody has told you the groups in advance. You just want the data to suggest them. This task is called clustering.

One of the most popular clustering methods is hierarchical clustering. If you have ever seen a heatmap with a tree drawn along its side, as in many biology and data science papers, that tree came from hierarchical clustering. The method has a nice property that sets it apart from other clustering methods such as K-means: you do not have to decide how many clusters you want before you start. It builds a whole tree of groupings, and you choose how many clusters to keep afterwards by looking at the tree (James et al. 2021, sec. 12.4.2).

This tutorial is written for readers who have taken a first statistics course and know some R. By the end you will be able to:

  1. explain, step by step, how hierarchical clustering works;
  2. compute it by hand and with R’s hclust() function, and check that the two agree;
  3. understand what the different linkage choices do and why they matter;
  4. read a dendrogram correctly, including a few common ways to misread one; and
  5. apply the method to a real dataset and interpret the result.

The tutorial follows the discussion of hierarchical clustering in An Introduction to Statistical Learning (James et al. 2021), and all code is in base R (R Core Team 2024), so nothing needs to be installed. You can click the “Code” buttons on the right to hide or show any code chunk.

2 Background

2.1 Unsupervised learning and distances

In regression or classification, every observation comes with an answer (a response) that we try to predict. Clustering is unsupervised: we only have the features, and the goal is to discover structure in them.

To say that two observations are “similar” we need a number that measures how far apart they are. The most common choice is Euclidean distance. For two observations \(x_i\) and \(x_j\) measured on \(p\) variables,

\[d(x_i, x_j) = \sqrt{\sum_{k=1}^{p} (x_{ik} - x_{jk})^2}.\]

In R, the function dist() computes all pairwise distances at once. For example, here are the distances between three points in the plane:

three <- rbind(a = c(0, 0), b = c(3, 4), c = c(6, 8))
dist(three)
##    a  b
## b  5   
## c 10  5

The distance between a and b is \(\sqrt{3^2 + 4^2} = 5\), as expected. The result is a lower triangle because the distance from a to b equals the distance from b to a.

2.2 Bottom-up (agglomerative) clustering

Hierarchical clustering can be done in two directions. Agglomerative (bottom-up) methods start with every observation alone and repeatedly merge the closest groups. Divisive (top-down) methods start with everything in one group and split. The bottom-up approach is by far the more common one, and it is what R’s hclust() does, so that is what we study here.

The idea is simple enough to say in one sentence: start with every point as its own cluster, and keep merging the two closest clusters until only one cluster is left. The only subtle part is what “closest” means when clusters contain several points, and that is the topic of the linkage section below.

3 The algorithm, step by step

Here is the algorithm in plain language, following James et al. (2021).

  1. Start with \(n\) observations, each in its own cluster, and compute all \(\binom{n}{2}\) pairwise distances.
  2. For \(i = n, n-1, \dots, 2\):
    1. Find the pair of clusters (among the \(i\) that currently exist) that is closest, and merge them. The distance between them is recorded as the height of this fusion in the dendrogram.
    2. Compute the new distances between the merged cluster and each of the remaining \(i - 2\) clusters.

After \(n - 1\) merges, everything is in one cluster, and the sequence of merges is the dendrogram.

3.1 A tiny worked example

To see this in action we use six points in the plane. Five of them form two small groups, and one point, F, is far away from everything.

pts <- data.frame(
  x = c(1.0, 1.5, 5.0, 5.5, 6.0, 9.0),
  y = c(1.0, 2.0, 1.0, 2.2, 1.4, 9.0),
  row.names = c("A", "B", "C", "D", "E", "F")
)
pts
##     x   y
## A 1.0 1.0
## B 1.5 2.0
## C 5.0 1.0
## D 5.5 2.2
## E 6.0 1.4
## F 9.0 9.0

The pairwise distances are:

d <- dist(pts)
round(d, 2)
##       A     B     C     D     E
## B  1.12                        
## C  4.00  3.64                  
## D  4.66  4.00  1.30            
## E  5.02  4.54  1.08  0.94      
## F 11.31 10.26  8.94  7.65  8.17

Step 1. The smallest entry in this table is the first pair to merge. We can find it in code instead of by eye:

dmat <- as.matrix(d)
diag(dmat) <- Inf                       # ignore the zero distance to itself
closest <- which(dmat == min(dmat), arr.ind = TRUE)[1, ]
rownames(dmat)[closest]                 # which two points?
## [1] "E" "D"
min(dmat)                               # at what distance?
## [1] 0.9433981

So the first fusion joins the two closest points, at a height equal to their distance.

Step 2: updating distances. Once, say, D and E are merged into a cluster, we need the distance from this new cluster to every other point. With complete linkage (defined in the next section), the distance from a point to a cluster is the largest distance from the point to any member of the cluster. For C and the cluster {D, E} that is

max(dmat["C", "D"], dmat["C", "E"])
## [1] 1.3

Repeating “find the closest pair, merge, update the distances” until one cluster remains is the whole algorithm. Rather than do all five rounds by hand, we let hclust() do it and print the record of what it did:

hc_tiny <- hclust(d, method = "complete")
data.frame(step = 1:5, hc_tiny$merge, height = round(hc_tiny$height, 2))
##   step X1 X2 height
## 1    1 -4 -5   0.94
## 2    2 -1 -2   1.12
## 3    3 -3  1   1.30
## 4    4  2  3   5.02
## 5    5 -6  4  11.31

In the merge columns, a negative number \(-k\) means “observation number \(k\)” (so \(-1\) is A), and a positive number \(j\) means “the cluster created at step \(j\)”. Reading row by row, we get the order of fusions and the height at which each happened.

par(mfrow = c(1, 2), mar = c(4, 4, 3, 1))
plot(pts, pch = 19, cex = 1.6, col = pal[1], xlim = c(0, 10), ylim = c(0, 10),
     main = "The data")
text(pts$x + 0.35, pts$y + 0.35, rownames(pts), cex = 1.1)
plot(hc_tiny, hang = -1, main = "The dendrogram", xlab = "", sub = "",
     ylab = "Height (fusion distance)")
Figure 1. Left: six points in the plane. Right: the dendrogram that complete-linkage hierarchical clustering builds from them.

Figure 1. Left: six points in the plane. Right: the dendrogram that complete-linkage hierarchical clustering builds from them.

Notice how the picture on the right encodes the steps above. Every observation is a leaf at the bottom. Pairs that merged early (low height) are joined by short branches near the bottom, and groups that merged late are joined high up. The lone point F merges last, at a very large height, which tells us it is an outlier compared with the two groups.

4 What does “closest” mean for clusters? Linkage

Distances between single points are easy. Once clusters contain several points, we must decide how to measure the distance between two groups of points. This choice is called the linkage, and it can change the result a lot. The four common choices, as described in James et al. (2021), are:

Linkage Distance between clusters \(A\) and \(B\) Behavior
Complete the largest distance between a point in \(A\) and a point in \(B\) tends to make compact, similar-sized clusters
Single the smallest distance between a point in \(A\) and a point in \(B\) can make long, stringy clusters (“chaining”)
Average the mean of all pairwise distances between \(A\) and \(B\) a compromise between the two
Centroid the distance between the two cluster means popular in genomics, but can produce inversions (see below)

In formulas, with \(|A|\) for the number of points in \(A\):

\[d_{\text{complete}}(A,B) = \max_{a\in A,\, b\in B} d(a,b), \qquad d_{\text{single}}(A,B) = \min_{a\in A,\, b\in B} d(a,b),\]

\[d_{\text{average}}(A,B) = \frac{1}{|A|\,|B|}\sum_{a\in A}\sum_{b\in B} d(a,b).\]

Average linkage is also known as UPGMA (James et al. 2021). A fifth option you will see in R is Ward’s method, which merges the pair of clusters that increases the total within-cluster variance the least (Ward 1963). In R it is method = "ward.D2", which is the version that matches Ward’s original criterion when used with Euclidean distances (Murtagh and Legendre 2014).

A word about the “inversion” problem with centroid linkage: because the distance between centroids can decrease after a merge, a fusion can occur at a lower height than an earlier one, so the dendrogram has branches that go the wrong way. This is one reason many people prefer complete, average, or Ward linkage (James et al. 2021).

4.1 Seeing the difference on synthetic data

To see how linkage affects the result, we make a synthetic dataset with three groups. Two of the groups are connected by a thin bridge of points between them, which is exactly the situation where single linkage struggles.

set.seed(607)
blob1  <- cbind(rnorm(30, 0, 0.5),   rnorm(30, 0, 0.5))
blob2  <- cbind(rnorm(30, 5, 0.5),   rnorm(30, 0, 0.5))
blob3  <- cbind(rnorm(30, 2.5, 0.5), rnorm(30, 4.5, 0.5))
bridge <- cbind(seq(1, 4, length.out = 6), rnorm(6, 0, 0.1))   # thin chain between blob1 and blob2
X <- rbind(blob1, blob2, blob3, bridge)
colnames(X) <- c("x1", "x2")
dim(X)
## [1] 96  2

We run the same data through three linkages and cut each tree into three clusters:

D <- dist(X)
methods <- c("complete", "average", "single")
par(mfrow = c(2, 3), mar = c(4, 4, 3, 1))
for (m in methods) {
  hc <- hclust(D, method = m)
  plot(hc, labels = FALSE, hang = -1, main = paste(m, "linkage"),
       xlab = "", sub = "", ylab = "Height")
  rect.hclust(hc, k = 3, border = pal[1:3])
}
for (m in methods) {
  cl <- cutree(hclust(D, method = m), k = 3)
  plot(X, col = pal[cl], pch = 19, xlab = "x1", ylab = "x2",
       main = paste(m, "linkage, k = 3"))
}
Figure 2. The same 96 points clustered with complete, average, and single linkage, each cut into 3 clusters. Top: the dendrograms (leaves not labeled because there are too many). Bottom: the points colored by cluster. Single linkage is the only one that is fooled by the bridge.

Figure 2. The same 96 points clustered with complete, average, and single linkage, each cut into 3 clusters. Top: the dendrograms (leaves not labeled because there are too many). Bottom: the points colored by cluster. Single linkage is the only one that is fooled by the bridge.

With complete and average linkage, the three clusters match the three blobs, and the bridge points are split between the two blobs they lie closest to. With single linkage, the thin bridge acts like a chain of stepping stones. The distance between two clusters is the smallest gap between them, and the bridge makes that gap tiny everywhere, so the two bridged blobs get glued into one big cluster. With that cluster taking up two of our three slots, the third blob is left to be split, and a single stray point gets peeled off as a cluster of its own. This is the chaining effect, and it is the main reason single linkage is used less often.

5 Computing it from scratch

hclust() is fast and reliable, but it is a black box until you have written the algorithm yourself. Here is a deliberately simple implementation that follows the steps from the previous sections. It is slow (it recomputes all cluster distances at every step), but it is short and easy to read.

my_hclust <- function(d, method = c("complete", "single", "average")) {
  method <- match.arg(method)
  link <- switch(method, complete = max, single = min, average = mean)
  D <- as.matrix(d)
  n <- nrow(D)

  members <- as.list(seq_len(n))   # step 1: every observation starts as its own cluster
  heights <- numeric(n - 1)        # fusion heights, in order
  partitions <- vector("list", n - 1)

  for (step in seq_len(n - 1)) {
    k <- length(members)
    best <- Inf
    # step 2a: look at every pair of current clusters and keep the closest pair
    for (i in 1:(k - 1)) {
      for (j in (i + 1):k) {
        dij <- link(D[members[[i]], members[[j]]])  # linkage = how we measure cluster distance
        if (dij < best) { best <- dij; bi <- i; bj <- j }
      }
    }
    heights[step] <- best                             # record the height of this fusion
    members[[bi]] <- c(members[[bi]], members[[bj]])  # merge the pair into one cluster
    members[[bj]] <- NULL

    # remember the cluster labels after this merge (so we can "cut the tree" later)
    memb <- integer(n)
    for (g in seq_along(members)) memb[members[[g]]] <- g
    partitions[[step]] <- memb
  }
  list(height = heights, partitions = partitions)
}

Step 2b (updating the distances) happens implicitly. Instead of storing a distance matrix that we update, we recompute the distance between clusters from the original observations at each step, using the linkage function link. That is slower but makes the definition of each linkage visible in one line.

Now we compare our version with hclust() on the 96-point synthetic dataset. We check two things: the heights of the fusions, and the 3-cluster partition obtained by cutting the tree.

same_partition <- function(a, b) all(outer(a, a, "==") == outer(b, b, "=="))

check <- sapply(methods, function(m) {
  mine <- my_hclust(D, m)
  ref  <- hclust(D, m)
  c(`heights match`   = isTRUE(all.equal(mine$height, ref$height)),
    `3 clusters match` = same_partition(mine$partitions[[nrow(X) - 3]], cutree(ref, 3)))
})
check
##                  complete average single
## heights match        TRUE    TRUE   TRUE
## 3 clusters match     TRUE    TRUE   TRUE

Every entry is TRUE, so our short loop reproduces hclust() exactly, for all three linkages. This is a good moment to appreciate how little there is to the method: a nested loop to find the closest pair, a merge, and repeat.

(The “3 clusters match” check uses partitions[[n - 3]] because after \(n - 3\) merges exactly 3 clusters are left. The helper same_partition() compares two labelings without caring which cluster is called 1, 2, or 3.)

6 Reading a dendrogram

6.1 Heights tell you how different two groups are

The vertical axis of a dendrogram is the height at which clusters were fused. It is the distance (under the chosen linkage) between the two clusters at the moment they were merged. Low fusions mean “very similar”, and high fusions mean “quite different”.

6.2 Cutting the tree gives clusters

A dendrogram contains every possible number of clusters at once, from \(n\) (cut at the very bottom) to 1 (cut above the top). To get a particular clustering, draw a horizontal line and keep the branches that hang below it, as in Figure 3. Cutting low gives many small clusters, and cutting high gives a few large ones. In R you can cut by number of clusters with cutree(hc, k = 3) or by height with cutree(hc, h = 2).

hc3 <- hclust(dist(rbind(blob1, blob2, blob3)), method = "complete")
cut_h <- 4                                       # the height we choose to cut at
cl3 <- cutree(hc3, h = cut_h)

par(mfrow = c(1, 2), mar = c(4, 4, 3, 1))
plot(hc3, labels = FALSE, hang = -1, main = "Cut at height 4", xlab = "", sub = "",
     ylab = "Height")
abline(h = cut_h, lty = 2, col = "firebrick", lwd = 2)
plot(rbind(blob1, blob2, blob3), col = pal[cl3], pch = 19, xlab = "x1", ylab = "x2",
     main = paste(length(unique(cl3)), "clusters"))
Figure 3. Cutting a dendrogram. The dashed line is the cut height; each branch it crosses becomes one cluster. The colored points on the right show the resulting 3 clusters.

Figure 3. Cutting a dendrogram. The dashed line is the cut height; each branch it crosses becomes one cluster. The colored points on the right show the resulting 3 clusters.

How do we choose where to cut? There is no single right answer. A common rule of thumb is to look for a long vertical stretch with no fusions: if the tree stays at “3 clusters” over a wide range of heights, then those three groups are well separated from each other. In Figure 3 the last two fusions happen at heights of about 6.7 and 7.2, while the one before them happens at about 2.8, so cutting anywhere between roughly 3 and 6.5 gives the same three clusters.

6.3 A common mistake: reading closeness from the horizontal axis

The left-to-right order of the leaves carries no meaning. At every fusion, the two branches could be swapped without changing the tree. Two leaves that sit next to each other in the plot may be very different, and two leaves far apart may be very similar. The only trustworthy information is the height at which two observations first end up in the same cluster.

The next figure shows the same tree from our six-point example, drawn twice, with every branch order reversed in the second drawing.

dend <- as.dendrogram(hc_tiny)
par(mfrow = c(1, 2), mar = c(3, 4, 3, 1))
plot(dend, main = "Original order", ylab = "Height")
plot(rev(dend), main = "All branches flipped", ylab = "Height")
Figure 4. The same dendrogram drawn two ways. Reversing the order of the branches changes which leaves are next to each other but not the tree: every pair of points still fuses at exactly the same height.

Figure 4. The same dendrogram drawn two ways. Reversing the order of the branches changes which leaves are next to each other but not the tree: every pair of points still fuses at exactly the same height.

In both drawings, A and B fuse at the same height, and F joins last at the same height. Only the left-to-right layout changed. Notice also that B and C sit side by side in both drawings, yet they do not end up in the same cluster until a height of about 5, while D and E (also neighbors) fuse below 1. Being neighbors in the picture tells you nothing; the fusion height does. (Software has to pick some order to draw leaves, so the order you see is an artifact of the plotting algorithm, not a finding.)

7 A real dataset: violent crime in US states

Now we apply everything to real data. The built-in USArrests dataset has data on 50 US states from 1973 (McNeil 1977):

  • Murder, Assault, Rape: arrests per 100,000 residents;
  • UrbanPop: percent of the population living in urban areas.
head(USArrests)
##            Murder Assault UrbanPop Rape
## Alabama      13.2     236       58 21.2
## Alaska       10.0     263       48 44.5
## Arizona       8.1     294       80 31.0
## Arkansas      8.8     190       50 19.5
## California    9.0     276       91 40.6
## Colorado      7.9     204       78 38.7

Our question is: which states look alike in terms of these four variables?

7.1 Why we must scale the variables first

Distances depend on the units of the variables. Look at how different the variances are:

round(apply(USArrests, 2, var), 1)
##   Murder  Assault UrbanPop     Rape 
##     19.0   6945.2    209.5     87.7

Assault has a variance of several thousand, while Murder has a variance of about 19. If we compute Euclidean distances on the raw data, Assault will dominate everything, simply because it is measured in larger numbers, not because it matters more. The standard fix is to standardize each variable to mean 0 and standard deviation 1 with scale() (James et al. 2021):

X_us <- scale(USArrests)
round(apply(X_us, 2, sd), 2)    # every variable now has standard deviation 1
##   Murder  Assault UrbanPop     Rape 
##        1        1        1        1

7.2 Clustering the states

hc_us <- hclust(dist(X_us), method = "complete")
par(mar = c(1, 4, 3, 1))
plot(hc_us, cex = 0.7, hang = -1, main = "US states clustered by crime and urbanization",
     xlab = "", sub = "", ylab = "Height")
rect.hclust(hc_us, k = 4, border = pal[1:4])
Figure 5. Complete-linkage hierarchical clustering of the 50 US states on the standardized USArrests data. The colored boxes show the cut into 4 clusters.

Figure 5. Complete-linkage hierarchical clustering of the 50 US states on the standardized USArrests data. The colored boxes show the cut into 4 clusters.

We cut the tree into four clusters, and we can see which states fall in each:

cl_us <- cutree(hc_us, k = 4)
# cutree() numbers clusters in the order it meets the states; renumber them from left to
# right along the dendrogram so the numbers match the colored boxes in Figure 5
cl_us <- match(cl_us, unique(cl_us[hc_us$order]))
names(cl_us) <- rownames(X_us)
table(cl_us)
## cl_us
##  1  2  3  4 
## 10 21 11  8
split(names(cl_us), cl_us)
## $`1`
##  [1] "Idaho"         "Iowa"          "Maine"         "Montana"      
##  [5] "Nebraska"      "New Hampshire" "North Dakota"  "South Dakota" 
##  [9] "Vermont"       "West Virginia"
## 
## $`2`
##  [1] "Arkansas"      "Connecticut"   "Delaware"      "Hawaii"       
##  [5] "Indiana"       "Kansas"        "Kentucky"      "Massachusetts"
##  [9] "Minnesota"     "Missouri"      "New Jersey"    "Ohio"         
## [13] "Oklahoma"      "Oregon"        "Pennsylvania"  "Rhode Island" 
## [17] "Utah"          "Virginia"      "Washington"    "Wisconsin"    
## [21] "Wyoming"      
## 
## $`3`
##  [1] "Arizona"    "California" "Colorado"   "Florida"    "Illinois"  
##  [6] "Maryland"   "Michigan"   "Nevada"     "New Mexico" "New York"  
## [11] "Texas"     
## 
## $`4`
## [1] "Alabama"        "Alaska"         "Georgia"        "Louisiana"     
## [5] "Mississippi"    "North Carolina" "South Carolina" "Tennessee"

To understand what each cluster represents, we compute the average of each variable in the original units within every cluster:

round(aggregate(USArrests, by = list(cluster = cl_us), FUN = mean), 1)
##   cluster Murder Assault UrbanPop Rape
## 1       1    3.2    78.7     49.3 11.6
## 2       2    5.9   134.5     70.8 18.6
## 3       3   11.1   264.1     79.1 32.6
## 4       4   14.1   252.8     53.5 24.5

Reading this table next to the lists of states gives each cluster a “personality”.

  • Cluster 1 (10 states, such as Idaho, Iowa, Maine, and Vermont) has the lowest rate for every crime and the smallest urban share.
  • Cluster 2 (21 states, such as Ohio, Virginia, and Massachusetts) sits in the middle on everything.
  • Cluster 3 (11 states, such as California, New York, Texas, and Florida) has the highest assault and rape rates and the most urban populations.
  • Cluster 4 (8 states: Alabama, Alaska, Georgia, Louisiana, Mississippi, North Carolina, South Carolina, and Tennessee) has the highest murder rate, with a below-average urban share.

The clustering did not know any of these labels, or where the states are; it only saw four numbers per state.

7.3 What happens if we skip scaling?

To make the point about scaling concrete, here is the same analysis on the raw data:

hc_raw <- hclust(dist(USArrests), method = "complete")
par(mfrow = c(1, 2), mar = c(1, 4, 3, 1))
plot(hc_us,  labels = FALSE, hang = -1, main = "Scaled", xlab = "", sub = "", ylab = "Height")
plot(hc_raw, labels = FALSE, hang = -1, main = "Not scaled", xlab = "", sub = "", ylab = "Height")
Figure 6. Left: dendrogram on standardized data. Right: dendrogram on raw data (state labels omitted; note the different height scales). Without scaling, the tree is driven almost entirely by Assault.

Figure 6. Left: dendrogram on standardized data. Right: dendrogram on raw data (state labels omitted; note the different height scales). Without scaling, the tree is driven almost entirely by Assault.

The two trees have quite different shapes. We can also measure how much the 4-cluster solutions agree:

table(scaled = cutree(hc_us, 4), raw = cutree(hc_raw, 4))
##       raw
## scaled  1  2  3  4
##      1  5  2  0  1
##      2  8  2  0  1
##      3  1 10 10  0
##      4  0  0 10  0

If scaling made no difference, each row of this table would have a single nonzero entry. Instead, states are shuffled among clusters. Which one is “right” depends on the question you are asking, but the unscaled version lets a single variable decide, which is usually not what we want.

7.4 The connection to heatmaps

Finally, we return to the heatmaps mentioned in the introduction. R’s heatmap() function runs hierarchical clustering on the rows (states) and the columns (variables), reorders both so that similar ones are next to each other, and draws the dendrograms in the margins.

heatmap(X_us,
        hclustfun = function(x) hclust(x, method = "complete"),
        scale = "none",
        col = colorRampPalette(c("#0072B2", "white", "#D55E00"))(50),
        margins = c(6, 9), cexRow = 0.6)
Figure 7. A heatmap of the standardized USArrests data. Rows (states) and columns (variables) are reordered by hierarchical clustering; the dendrograms on the margins are the same kind of tree we built above. Red means above average, blue means below average.

Figure 7. A heatmap of the standardized USArrests data. Rows (states) and columns (variables) are reordered by hierarchical clustering; the dendrograms on the margins are the same kind of tree we built above. Red means above average, blue means below average.

Each row is a state and each column is a variable. Because the rows are ordered by the dendrogram, states with similar profiles form visible blocks of color. The tree on top shows which variables move together; here, the three crime variables join each other first (murder and assault, then rape), and urban population is the odd one out, joining last.

8 Practical choices and pitfalls

Hierarchical clustering looks like a method with no settings, but it involves several decisions, each of which can change the answer (James et al. 2021):

  • Scale or not? Standardize variables measured in different units, as we did for USArrests, unless there is a reason to preserve the original scale.
  • Which dissimilarity? We used Euclidean distance. For some problems a correlation-based distance, which groups observations with similar shapes regardless of level, is more meaningful.
  • Which linkage? Complete, average, and Ward’s methods tend to give balanced, interpretable trees. Single linkage is prone to chaining.
  • Where to cut? This is a judgment call. The dendrogram helps, but it does not tell you “the” number of clusters.
  • Is a hierarchy appropriate? The method forces clusters to be nested: the 2-cluster solution is always a merge of the 3-cluster solution. That is not always realistic. For example, a group of people split best into three clusters by nationality might be split best into two clusters by sex, and these two groupings are not nested.
  • Robustness. Clustering can be sensitive to a few observations. It is good practice to check whether the clusters survive removing some data or changing the linkage.

9 Conclusion

Hierarchical clustering turns a table of distances into a tree. The recipe is short: start with every observation on its own, repeatedly merge the two closest clusters, and record the height of every merge. The tree (the dendrogram) shows the full sequence of merges, and cutting it at a chosen height gives a clustering with as many groups as you like. The linkage decides what “closest” means for groups of points and strongly influences the shape of the tree, scaling decides which variables count, and the horizontal order of leaves is not meaningful.

We saw each of these ideas in code: a hand-worked six-point example, a from-scratch implementation that matched hclust() exactly, a synthetic experiment showing how single linkage chains through a bridge, and a real-data analysis of the US states that ended in a heatmap. If you want to go further, the natural next steps are K-means clustering, which needs the number of clusters up front, and the chapter on unsupervised learning in James et al. (2021), which covers these topics in more depth.

References

James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani. 2021. An Introduction to Statistical Learning with Applications in R. 2nd ed. Springer. https://www.statlearning.com.
McNeil, Donald R. 1977. Interactive Data Analysis. Wiley.
Murtagh, Fionn, and Pierre Legendre. 2014. “Ward’s Hierarchical Agglomerative Clustering Method: Which Algorithms Implement Ward’s Criterion?” Journal of Classification 31 (3): 274–95.
R Core Team. 2024. R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing. https://www.R-project.org/.
Ward, Joe H. 1963. “Hierarchical Grouping to Optimize an Objective Function.” Journal of the American Statistical Association 58 (301): 236–44.
Xie, Yihui, Christophe Dervieux, and Emily Riederer. 2020. R Markdown Cookbook. Chapman and Hall/CRC. https://bookdown.org/yihui/rmarkdown-cookbook.

This tutorial was written in R Markdown (Xie et al. 2020).