You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言层次聚类问题:手动距离矩阵构建单连接树状图报错

Fixing Single Linkage Dendrogram Error with Your 11x11 Distance Matrix

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:

  1. Symmetric: mat[i,j] must equal mat[j,i] for all i,j
  2. 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 dist object: Passing the full 11x11 matrix directly to hclust() can cause parsing issues, even if the matrix is valid. Converting to dist resolves this.
  • Asymmetric matrix: If your manual entry had a typo (e.g., mat[1,6] = 1 but mat[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:05:05