【问题标题】:Manipulating cutree object in R to segment original dataframe在R中操作cutree对象以分割原始数据帧
【发布时间】:2013-08-23 03:03:18
【问题描述】:

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

...瞧,我完成了。

想法/建议?

【问题讨论】:

    标签: r dataframe data-manipulation hclust


    【解决方案1】:

    解决方法如下:

    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"
    

    【讨论】:

    • 谢谢!我必须做更多的工作来使用which 来操作非数据框对象。
    【解决方案2】:

    为什么不直接

    data$clusterID <- treecuts
    

    然后像往常一样子集数据?

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      相关资源
      最近更新 更多