如何在R中使用k-means聚类技术获得簇数对应的数据?

时间:2011-11-26 14:10:46

标签: r cluster-analysis k-means

我通过k-means聚类方法聚类数据,如何使用R中的k-means聚类技术得到聚类数对应于数据?为了让每条记录属于哪个集群。

示例 12 32 13 => 1. 12,13 2. 32

3 个答案:

答案 0 :(得分:11)

听起来您正在尝试访问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

解决评论中的问题

您可以通过执行以下操作将群集编号“映射”到原始数据:

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

答案 1 :(得分:7)

@ 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)

祝你的群集好运

答案 2 :(得分:0)

我们喜欢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.

帮助中有一个示例可以准确显示其工作原理。