我正在使用 R 的内置相关矩阵和层次聚类方法将每日销售数据分成 10 个集群。然后,我想按集群创建汇总的每日销售数据。我已经创建了一个 cutree()
对象,但是我很难提取 cutree
对象中的列名,例如簇号为 1 .
为简单起见,我将使用 EuStockMarkets
数据集并将树分成两段;请记住,我在这里处理数千列,因此需要可扩展:
data=as.data.frame(EuStockMarkets)
corrMatrix<-cor(data)
dissimilarity<-round(((1-corrMatrix)/2), 3)
distSimilarity<-as.dist(dissimilarity)
hirearchicalCluster<-hclust(distSimilarity)
treecuts<-cutree(hirearchicalCluster, k=2)
现在,我卡住了。例如,我只想从 treecuts
中提取列名,其中簇号等于 1。但是,cutree()
生成的对象不是 DataFrame,这使得设置子集变得困难。我试图将 treecuts
转换为数据框,但 R 没有为行名称创建列,它所做的只是将数字强制转换为名为 treecuts的行
。
我想做以下操作:
....Code that converts treecuts into a data frame called "treeIDs" with the
columns "Index" and "Cluster"......
cluster1Columns<-colnames(treeIDs[Cluster==1, ])
cluster1DF<-data[ , (colnames(data) %in% cluster1Columns)]
rowSums(cluster1DF)
...瞧,我完成了。
想法/建议?
最佳答案
解决方法如下:
names(treecuts[which(treecuts[1:4]==1)])
[1] "DAX" "SMI" "FTSE"
如果你想,比如说,对于集群 2(或更高),你可以使用 %in%
names(treecuts[which(treecuts[1:4] %in% c(1,2))])
[1] "DAX" "SMI" "CAC" "FTSE"
关于r - 操作 R 中的 cutree 对象以分割原始数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345606/