3

我用 cutree() 将我的 hclust() 树聚类成几个组。现在我想要一个函数来 hclust() 几个 groupmembers 作为 hclust() ...另外:

我将一棵树分成 168 个组,我想要 168 个 hclust() 树……我的数据是 1600*1600 矩阵。

我的数据太大了,所以我举个例子

m<-matrix(1:1600,nrow=40)
#m<-as.matrix(m) // I know it isn't necessary here
m_dist<-as.dist(m,diag = FALSE )


m_hclust<-hclust(m_dist, method= "average")
plot(m_hclust)

groups<- cutree(m_hclust, k=18)

现在我想绘制 18 棵树……一组一棵树。我已经尝试了很多..

4

1 回答 1

8

我提前警告你,对于这么大的树,可能大多数解决方案运行起来都会有点慢。但这是一种解决方案(使用dendextend R 包):

m<-matrix(1:1600,nrow=40)
#m<-as.matrix(m) // I know it isn't necessary here
m_dist<-as.dist(m,diag = FALSE )
m_hclust<-hclust(m_dist, method= "complete")
plot(m_hclust)
groups <- cutree(m_hclust, k=18)

# Get dendextend
install.packages.2 <- function (pkg) if (!require(pkg)) install.packages(pkg);
install.packages.2('dendextend')
install.packages.2('colorspace')
library(dendextend)
library(colorspace)

# I'll do this to just 4 clusters for illustrative purposes
k <- 4
cols <- rainbow_hcl(k)
dend <- as.dendrogram(m_hclust)
dend <- color_branches(dend, k = k)
plot(dend)
labels_dend <- labels(dend)
groups <- cutree(dend, k=4, order_clusters_as_data = FALSE)
dends <- list()
for(i in 1:k) {
    labels_to_keep <- labels_dend[i != groups]
    dends[[i]] <- prune(dend, labels_to_keep)
}

par(mfrow = c(2,2))
for(i in 1:k) { 
    plot(dends[[i]], 
        main = paste0("Tree number ", i))
}
# p.s.: because we have 3 root only trees, they don't have color (due to a "missing feature" in the way R plots root only dendrograms)

在此处输入图像描述

让我们在“更好”的树上再做一次:

m_dist<-dist(mtcars,diag = FALSE )
m_hclust<-hclust(m_dist, method= "complete")
plot(m_hclust)

# Get dendextend
install.packages.2 <- function (pkg) if (!require(pkg)) install.packages(pkg);
install.packages.2('dendextend')
install.packages.2('colorspace')
library(dendextend)
library(colorspace)

# I'll do this to just 4 clusters for illustrative purposes
k <- 4
cols <- rainbow_hcl(k)
dend <- as.dendrogram(m_hclust)
dend <- color_branches(dend, k = k)
plot(dend)
labels_dend <- labels(dend)
groups <- cutree(dend, k=4, order_clusters_as_data = FALSE)
dends <- list()
for(i in 1:k) {
    labels_to_keep <- labels_dend[i != groups]
    dends[[i]] <- prune(dend, labels_to_keep)
}

par(mfrow = c(2,2))
for(i in 1:k) { 
    plot(dends[[i]], 
        main = paste0("Tree number ", i))
}
# p.s.: because we have 3 root only trees, they don't have color (due to a "missing feature" in the way R plots root only dendrograms)

在此处输入图像描述

于 2016-01-23T04:19:02.013 回答