Kmeans 聚类 - 数据已分组为产品

Kmeans Clustering - data already grouped as products

我有以下数据框

 'data.frame':  88 obs. of  16 variables:
 $ product1: num  212 283 364 357 376 ...
 $ product2: num  5025 4899 4828 4519 4340 ...
 $ product3: num  4295 3745 3790 3868 4066 ...
 $ product4: num  550 557 593 568 556 ...
 $ product5: num  0 0 0 0 0 ...
 $ product6: num  3484 3205 5243 5183 4784 ...
 $ product7: num  0 0 992 1066 983 ...
 $ product8: num  0 0 0 0 0 0 0 0 0 0 ...
 $ product9: num  0 0 0 0 0 0 0 0 0 0 ...
 $ product10: num  0 0 0 0 0 0 0 0 0 0 ...
 $ product11: num  0 0 0 0 0 0 0 0 0 0 ...
 $ product12: num  0 0 0 0 0 0 0 0 0 0 ...
 $ product13: num  0 0 0 0 0 0 0 0 0 0 ...
 $ product14: num  0 0 0 0 0 0 0 0 0 0 ...
 $ product15: num  0 0 0 0 0 0 0 0 0 0 ...
 $ product16: num  0 0 0 0 0 0 0 0 0 0 ...

我想做的是根据产品的销售额将产品分为 3 组,例如:

cluster 1: products 1, 2, 3, 15, 16
cluster 2: products 4, 5, 6, 7, 8, 9, 10
cluster 3: products 11, 12, 13, 14

但是,我正在努力在 R 上写这个。我现在得到的是以下内容:

km <- kmeans(dataFrame, 3)
km$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 2 2 2 2 2 2 2 2 2 2 2 2 2 2
[41] 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
[81] 3 3 3 3 3 3 3 3

问题是,我应该如何编写代码才能获得上面打印的 16 种不同产品的 3 个集群?

我在 R 中生成了 kmeans 聚类的示例。这里的数据集由 3 个变量(3 列)组成,kmeans 用于将样本分为 4 组。第一个输出显示 3 个变量和 4 个集群的集群中心。请注意,如果您需要转置数据,请在 R 中使用 t。第二个输出显示集群的样本数。

set.seed(1); d <- matrix(rnorm(90), ncol=3)
kd <- kmeans(d, centers=4)
cluster <- kd$cluster
dd <- as.data.frame(cbind(d, cluster))
t(aggregate(dd, by=list(dd$cluster), FUN=mean))[c(1,5)*-1,]

         [,1]        [,2]        [,3]       [,4]
V1  0.8321043 -0.01501747 -0.09144934 -1.8916013
V2  0.0121109 -0.51743551  0.85714652 -0.5389448
V3 -0.4478400  0.17132066  0.99685057 -0.9206161

table(kd$cluster)

 1  2  3  4 
11  6 10  3 

现在,您有 81 个观测值和 16 个变量。

K 均值聚类 *观察值”,而不是变量。

因此,您需要转置数据。