我使用k-means聚类方法对数据进行聚类,如何在R中使用k-means聚类技术获得与数据对应的聚类数?以便获得每条记录属于哪个簇。
示例12 32 13 => 1. 12,13 2. 32
发布于 2011-11-26 22:56:52
听起来您正在尝试访问由kmeans()
返回的集群向量。在群集的帮助页面中:
A vector of integers (from 1:k) indicating the cluster to which each
point is allocated.
使用帮助页面上的示例:
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")
(cl <- kmeans(x, 2))
#Access the cluster vector
cl$cluster
> cl$cluster
[1] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
[45] 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[89] 1 1 1 1 1 1 1 1 1 1 1 1
在comments中解决问题的
您可以通过执行以下操作将集群编号“映射”到原始数据:
out <- cbind(x, clusterNum = cl$cluster)
head(out)
x y clusterNum
[1,] -0.42480483 -0.2168085 2
[2,] -0.06272004 0.3641157 2
[3,] 0.08207316 0.2215622 2
[4,] -0.19539844 0.1306106 2
[5,] -0.26429056 -0.3249288 2
[6,] 0.09096253 -0.2158603 2
cbind
是用于列绑定的函数,还有一个用于行的rbind
函数。有关?cbind
和?rbind
的更多详细信息,请参阅其帮助页面。
发布于 2011-11-26 22:52:50
@ Java提问者
您可以通过如下方式访问集群数据:
> data_clustered <- kmeans(data)
> data_clustered$cluster
data_clustered$cluster
是一个向量,其长度为数据中原始记录数的长度。每一项都是针对该行的。
要获取属于集群1的所有记录,请执行以下操作:
> data$cluster <- data_clustered$cluster
> data_clus_1 <- data[data$cluster == 1,]
集群数量:
> max(data$cluster)
祝你的集群好运
发布于 2011-11-26 22:54:41
我们喜欢Stack Overflow上的可重现的例子。否则我们只是猜测而已。
我猜您在stats包中使用的是kmeans。
我进一步猜测你还没有读过文档帮助(Kmeans),它是这样写的:
Value:
an object of class 'kmeans' which is a list with components:
cluster: A vector of integers indicating the cluster to which each point is allocated.
在帮助中有一个示例,它确切地向您展示了它是如何工作的。
https://stackoverflow.com/questions/8278966
复制相似问题