R/RStudio中:如何查看基于拼接属性的聚类分组对应项目
Map Items to Their Clusters
Your current code correctly clusters the unique concatenated attribute strings, but to link each original Item to its cluster, you just need to merge the clustering results back with your original dataset. Here's how to do it step by step:
Step 1: Refine Your Clustering Code (For Clarity)
First, let's adjust your existing code to name the cluster column explicitly, making it easier to work with later:
# Your original clustering logic, with a clearly named cluster column unique_attr <- unique(as.character(data$ConcatenatedAttributes)) dist_matrix <- stringdistmatrix(unique_attr, unique_attr, method = "jw") rownames(dist_matrix) <- unique_attr hc <- hclust(as.dist(dist_matrix)) cluster_assignments <- data.frame( ConcatenatedAttributes = unique_attr, ClusterNumber = cutree(hc, k = 200) )
Step 2: Merge Cluster Assignments with Original Items
Now, join this cluster assignment table with your original data to associate each Item with its corresponding cluster:
# Link each item to its cluster using the concatenated attributes item_clusters <- merge( x = data[, c("Item", "ConcatenatedAttributes")], y = cluster_assignments, by = "ConcatenatedAttributes", all.x = TRUE # Guarantees every item gets a cluster, no missing entries ) # Clean up the result to match your desired format final_result <- item_clusters[, c("ClusterNumber", "Item")] # Optional: Sort by cluster number for easier inspection final_result <- final_result[order(final_result$ClusterNumber), ]
Why This Works
- The
mergeoperation connects each item's concatenated attribute string to the cluster it was assigned to in your hierarchical clustering. - Items with identical concatenated attributes will automatically be grouped into the same cluster, which aligns with your goal of finding similar items.
- Using
all.x = TRUEensures no items are excluded, even if there's an unexpected edge case (though this shouldn't happen if your original data andunique_attrare consistent).
You can now view final_result to see each Item paired with its ClusterNumber, exactly in the format you wanted.
内容的提问来源于stack exchange,提问作者DRSK
相关产品推荐
相关产品推荐

