R语言聚类循环报错修复:生成2-10类划分结果向量
Fixing the "number of items to replace is not a multiple of replacement length" Error in Your SOM Clustering Code
Hey there! Let's break down why your code is throwing that error and get it working exactly how you need it.
What's Causing the Error?
Your current code tries to assign the entire vector of cluster labels returned by cutree() to a single position somc[n] in a regular vector. Here's the core issue:
cutree(hclust(dist(som_model$codes[[1]])), n)returns a vector where each element is the cluster label for one of your SOM codebook vectors (its length equals the number of rows insom_model$codes[[1]]).somc[n]is just a single element slot in a vector—you can't stuff a whole vector into one slot, hence the mismatch error.
The Fix: Use a List to Store Cluster Vectors
You need a structure that can hold multiple vectors (one for each cluster count from 2 to 10). A list is perfect for this. Here's the corrected code:
# Initialize an empty list with 9 slots (for n=2 to 10) somc <- vector("list", length = 9) # Name the list elements for easy reference later names(somc) <- as.character(2:10) # Run the loop to populate each list element for (n in 2:10) { # Assign the cluster vector to the corresponding list slot somc[[as.character(n)]] <- cutree(hclust(dist(som_model$codes[[1]])), n) }
Even Cleaner: Use lapply Instead of a For Loop
If you prefer more idiomatic R code, you can skip the for loop entirely with lapply:
# Generate all cluster vectors in one go somc <- lapply(2:10, function(k) { cutree(hclust(dist(som_model$codes[[1]])), k) }) # Add names to keep track of which element corresponds to how many clusters names(somc) <- as.character(2:10)
How to Use the Result
Now you can access each cluster assignment vector easily:
somc[["2"]]gives you the 2-cluster partitionsomc[["5"]]gives you the 5-cluster partition- And so on up to
somc[["10"]]
内容的提问来源于stack exchange,提问作者Amri Muhaimin
相关产品推荐
相关产品推荐

