R语言层次聚类问题:手动距离矩阵构建单连接树状图报错
Hey there! Let's walk through solving this error step by step. First, let's make sure your distance matrix is properly defined and formatted for R's clustering functions.
Step 1: Correctly Define Your Distance Matrix
First, let's finish writing out your matrix code properly (you had a trailing ...):
# Define the 11x11 distance matrix mat <- matrix(c(0,1,2,3,3,1,2,2,2,3,2, 1,0,1,2,2,2,1,2,3,2,3, 2,1,0,1,1,2,2,1,2,3,3, 3,2,1,0,1,3,3,2,3,4,4, 3,2,1,1,0,3,3,2,3,4,4, 1,2,2,3,3,0,1,1,1,2,1, 2,1,2,3,3,1,0,1,2,1,2, 2,2,1,2,2,1,1,0,1,2,2, 2,3,2,3,3,1,2,1,0,1,1, 3,2,3,4,4,2,1,2,1,0,1, 2,3,3,4,4,1,2,2,1,1,0), nrow=11, byrow=TRUE)
Step 2: Verify the Distance Matrix is Valid
Distance matrices must satisfy two key rules for clustering:
- Symmetric:
mat[i,j]must equalmat[j,i]for all i,j - Diagonal values are 0: All elements on the main diagonal are 0 (your matrix already has this)
Check symmetry with this quick test:
all(mat == t(mat)) # Should return TRUE
If this returns FALSE, you have a typo in your manual matrix entry—double-check the values to fix mismatched pairs.
Step 3: Convert to a dist Object
R's hclust() function works best with a dist class object (a compressed representation of the distance matrix) instead of the full 11x11 matrix. Convert it like this:
dist_mat <- as.dist(mat)
Step 4: Build the Single Linkage Dendrogram
Now run the single linkage clustering and plot the dendrogram:
# Perform single linkage clustering hc_single <- hclust(dist_mat, method = "single") # Plot the dendrogram plot(hc_single, main = "Single Linkage Dendrogram (11 Vertices)")
Common Causes of Your Error
- Not using a
distobject: Passing the full 11x11 matrix directly tohclust()can cause parsing issues, even if the matrix is valid. Converting todistresolves this. - Asymmetric matrix: If your manual entry had a typo (e.g.,
mat[1,6] = 1butmat[6,1] = 2), this breaks the distance matrix rules and triggers errors. Use the symmetry check above to catch this.
Running these steps should give you a working single linkage dendrogram without errors!
内容的提问来源于stack exchange,提问作者user2095405

