Jav*_*ner 3 r cluster-analysis k-means
我通过k-means聚类方法对数据进行聚类,如何在R中使用k-means聚类技术得到簇数对应的数据?为了让每条记录属于哪个集群.
例
12 32 13 => 1. 12,13 2. 32
Cha*_*ase 11
听起来您正在尝试访问返回的集群向量kmeans().从群集的帮助页面:
A vector of integers (from 1:k) indicating the cluster to which each
point is allocated.
Run Code Online (Sandbox Code Playgroud)
使用帮助页面上的示例:
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
Run Code Online (Sandbox Code Playgroud)
在评论中解决问题
您可以通过执行以下操作将群集编号"映射"到原始数据:
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
Run Code Online (Sandbox Code Playgroud)
cbind是列绑定的函数,还有一个rbind行函数.有关更多详细信息?cbind,请?rbind分别参阅其帮助页面.
@Java提问者
您可以按如下方式访问群集数据:
> data_clustered <- kmeans(data)
> data_clustered$cluster
Run Code Online (Sandbox Code Playgroud)
data_clustered$cluster是一个向量,其长度与数据中的原始记录数相同.每个条目都是该行.
要获取属于群集1的所有记录:
> data$cluster <- data_clustered$cluster
> data_clus_1 <- data[data$cluster == 1,]
Run Code Online (Sandbox Code Playgroud)
集群数量:
> max(data$cluster)
Run Code Online (Sandbox Code Playgroud)
祝你的集群好运