切一个树状图

Cut a dendrogram

我有一个 dendrogram:

set.seed(10)
mat <- matrix(rnorm(20*10),nrow=20,ncol=10)
dend <- as.dendrogram(hclust(dist(mat)))

并给定深度截止:

我想剪掉该截断点右侧的所有分支。

depth.cutoff <- 4.75

我想剪掉虚线右边的所有分支:

plot(dend,horiz = TRUE)
abline(v=depth.cutoff,col="red",lty=2)

最后 dendrogram:

我得到的最接近的是使用 apedrop.tip,但问题是如果我的 depth.cutoff 包括所有叶子,如本例所示,它 returns NULL.

如果他们的 depth 低于 depth.cutoff,也许有人知道我是否以及如何从代表我的 dendrogramnested list 中删除元素?

或者,也许我可以将 dendrogram 转换为 data.frame,它还列出了每个 nodedepth(包括将 depth=0),从 data.frame 中删除所有带有 depth < depth.cutoff 的行,然后将其转换回 dendrogram?

cut 会在指定的高度砍树。它将 return upperlower 部分的列表

cut(dend, h = depth.cutoff)$upper

# $upper
# 'dendrogram' with 2 branches and 5 members total, at height 5.887262 
# 
# $lower
# $lower[[1]]
# 'dendrogram' with 2 branches and 6 members total, at height 4.515119 
# 
# $lower[[2]]
# 'dendrogram' with 2 branches and 2 members total, at height 3.789259 
# 
# $lower[[3]]
# 'dendrogram' with 2 branches and 5 members total, at height 3.837733 
# 
# $lower[[4]]
# 'dendrogram' with 2 branches and 3 members total, at height 3.845031 
# 
# $lower[[5]]
# 'dendrogram' with 2 branches and 4 members total, at height 4.298743


plot(cut(dend, h = depth.cutoff)$upper, horiz = T)

或许更直接的获取图片的方法是设置要绘制的限制。

plot(dend, horiz = TRUE, xlim=c(6,4.75))