【发布时间】:2012-01-06 21:58:54
【问题描述】:
我通过 k-means 聚类方法对数据进行聚类,如何在 R 中使用 k-means 聚类技术获得与数据相对应的聚类数?为了得到每条记录属于哪个簇。
示例
12 32 13 => 1. 12,13 2. 32
【问题讨论】:
标签: r cluster-analysis k-means
我通过 k-means 聚类方法对数据进行聚类,如何在 R 中使用 k-means 聚类技术获得与数据相对应的聚类数?为了得到每条记录属于哪个簇。
示例
12 32 13 => 1. 12,13 2. 32
【问题讨论】:
标签: r cluster-analysis k-means
听起来您正在尝试访问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
解决 cmets 中的问题
您可以通过执行以下操作将集群编号“映射”到原始数据:
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。
【讨论】:
@Java 提问者
您可以按如下方式访问集群数据:
> data_clustered <- kmeans(data)
> data_clustered$cluster
data_clustered$cluster是一个向量,长度为data中原始记录数。每个条目都针对该行。
获取属于集群 1 的所有记录:
> data$cluster <- data_clustered$cluster
> data_clus_1 <- data[data$cluster == 1,]
集群数量:
> max(data$cluster)
祝你的聚类好运
【讨论】:
我们喜欢 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.
帮助中有一个示例,可以准确地向您展示其工作原理。
【讨论】: