我是R的新手并试图处理一个kmeans对象。理想情况下,我想要的是获取数据中每个点的簇标签列表,并将标签替换为相应的中心。基本上,最后是一个矩阵,其中每个数据点由集群中心的值表示,它由kmeans放置。
有没有办法有效地执行此操作,而不是手动遍历每个条目并使用群集中心值替换群集标签?
谢谢!
答案 0 :(得分:3)
这就是你要追求的吗?从this answer扩展:
# make some data
x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(x) <- c("x", "y")
#
# do cluster analysis
(cl <- kmeans(x, 2))
#
# put cluster labels with data
out1 <- data.frame(cbind(x, clusterNum = cl$cluster))
#
# organise center coords to be ready for merging
centers <- data.frame(cbind(data.frame(cl$center[,1]),
data.frame(cl$center[,2]),
clusterNum=rownames(cl$center)))
#
# merge cluster center coords with data
out2 <- merge(out1, centers, all.x = TRUE)
#
# check output
out2
clusterNum x y cl.center...1. cl.center...2.
1 1 0.233161364 -0.04258146 0.01064895 0.01376516
2 1 -0.356284774 -0.59135602 0.01064895 0.01376516
3 1 -0.302272796 -0.24033113 0.01064895 0.01376516
4 1 -0.369299302 -0.24997660 0.01064895 0.01376516
5 1 -0.060454427 0.19711328 0.01064895 0.01376516
...
90 2 0.609833599 0.67729922 1.05184887 1.03445718
91 2 0.943306637 1.09420588 1.05184887 1.03445718
92 2 0.545053826 1.22620571 1.05184887 1.03445718
93 2 0.706921965 1.10326091 1.05184887 1.03445718
94 2 0.837644227 1.07121784 1.05184887 1.03445718
95 2 0.550863085 1.06977250 1.05184887 1.03445718
#
# Success! We have one dataframe that includes: raw data, cluster labels
# and cluster center coords
我使用merge
将群集中心与原始数据放在一起,但毫无疑问,有更有效的方法(例如,不需要重新组织cl$center
)。