[英]Manipulating cutree object in R to segment original dataframe
我使用R的內置關聯矩陣和層次聚類方法將每日銷售數據分成10個集群。 然后,我想通過集群創建聚集的每日銷售數據。 我已經創建了一個cutree()
對象,但是我cutree()
在例如提取簇號為1的cutree
對象中提取列名。
為簡單起見,我將使用EuStockMarkets
數據集並將樹切割成2段; 請記住,我正在使用數千列,因此需要可擴展:
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"
為什么不呢
data$clusterID <- treecuts
然后像往常一樣子集數據?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.