r - 操作 R 中的 cutree 对象以分割原始数据帧

标签 r dataframe data-manipulation hclust

我正在使用 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/

相关文章:

r - 通过计算特定字符来对字符串进行分组

python - pandas 从已经存在的标题中额外添加一个新标题?

google-sheets - 不使用 Excel 对 Tableau 的交叉表数据进行标准化(重新格式化)

Javascript JSON 数据操作库

r - 确定何时添加了 R 基本函数

r - 捕获错误然后分支逻辑

替换长度 > 2 的相同值序列

r - 如何在 R 中仅附加数据框的两列

r - 如何替换数据框列表中的单个值

r - 数据文件中不同行间隔的多个标题