是否有一种简单的方法可以在根处合并多个hclust对象(或树形图)?
我已尽可能完整地举例说明我的问题。
让我们说我想按区域聚集USArrests,然后联合所有最好的对象,将它们一起绘制在热图中。
USArrests
Northeast <- c("Connecticut", "Maine", "Massachusetts", "New Hampshire", "Rhode Island",
"Vermont", "New Jersey", "New York", "Pennsylvania")
Midwest <- c("Illinois", "Indiana", "Michigan", "Ohio", "Wisconsin",
"Iowa", "Kansas", "Minnesota", "Missouri", "Nebraska", "North Dakota",
"South Dakota")
South <- c("Delaware", "Florida", "Georgia", "Maryland", "North Carolina",
"South Carolina", "Virginia", "West Virginia",
"Alabama", "Kentucky", "Mississippi", "Tennessee", "Arkansas",
"Louisiana", "Oklahoma", "Texas")
West <- c("Arizona", "Colorado", "Idaho", "Montana", "Nevada", "New Mexico",
"Utah", "Wyoming", "Alaska", "California", "Hawaii", "Oregon", "Washington")
h1 <- hclust(dist(USArrests[Northeast,]))
h2 <- hclust(dist(USArrests[Midwest,]))
h3 <- hclust(dist(USArrests[South,]))
h4 <- hclust(dist(USArrests[West,]))
现在我有4个hclust对象(h1到h4)。我通常将它们合并如下:
hc <- as.hclust(merge(merge(merge(
as.dendrogram(h1), as.dendrogram(h2)), as.dendrogram(h3)),
as.dendrogram(h4)))
然后,为了绘制它们,我必须根据hclust对象重新排序矩阵,然后绘图(我添加了一些注释以使绘图更清晰):
usarr <- USArrests[c(Northeast, Midwest, South, West),]
region_annotation <- data.frame(Region = c(rep("Northeast", length(Northeast)),
rep("Midwest", length(Midwest)),
rep("South", length(South)),
rep("West", length(West))),
row.names = c(Northeast, Midwest, South, West))
pheatmap(usarr, cluster_rows = hc,
annotation_row = region_annotation)
总结:除了合并所有单独的hclusts之外,还有一种更简单的方法吗?
答案 0 :(得分:1)
要创建合并的hclust
对象,您可以在使用<<-
创建的自定义环境中安全地使用new.env
。
在不使用<<-
的情况下,可能还有其他两种方法可以一次创建两个合并对象。希望有人可以对它进行说明。
我尝试使用do.call('merge', list( dendrograms of h1, h2, h3, h4 )
。但它没有用,因为hclust
需要在顶部有两个分支而不是4个分支。
<强>代码:强>
library('pheatmap')
myenv <- new.env()
myenv$hc <- as.dendrogram( hclust( dist(USArrests[Northeast,])))
invisible( lapply( list( Midwest, South, West), function(x){
myenv$hc <<- merge( myenv$hc, as.dendrogram( hclust( dist( USArrests[ x, ]) )) )
NULL
} ) )
myenv$hc <- as.hclust(myenv$hc)
<强>图形:强>
pheatmap(usarr, cluster_rows = myenv$hc,
annotation_row = region_annotation)
答案 1 :(得分:1)
我最终制作了几个函数来更自动地完成这项工作。 (在我的版本中,我还添加了对相关“距离”的支持,所以它有点大)
hclust_semisupervised <- function(data, groups, dist_method = "euclidean",
dist_p = 2, hclust_method = "complete") {
hclist <- lapply(groups, function (group) {
hclust(dist(data[group,], method = dist_method, p = dist_p), method = hclust_method)
})
hc <- .merge_hclust(hclist)
data_reordered <- data[unlist(groups),]
return(list(data = data_reordered, hclust = hc))
}
.merge_hclust <- function(hclist) {
#-- Merge
d <- as.dendrogram(hclist[[1]])
for (i in 2:length(hclist)) {
d <- merge(d, as.dendrogram(hclist[[i]]))
}
as.hclust(d)
}
拥有USArrests和区域向量,我这样称呼hclust_semisupervised
:
semi_hc <- hclust_semisupervised(USArrests, list(Northeast, Midwest, South, West)
现在绘制热图:
pheatmap(semi_hc$data, cluster_rows = semi_hc$hclust,
annotation_row = region_annotation)