R:如何提取树形图的某个节点中的所有标签

时间:2018-03-17 13:11:16

标签: r nodes labels dendrogram members

我正在编写一个程序(作为其中的一部分)自动从输入数据集创建树形图。 对于每个节点/拆分,我想提取所有该节点下的标签树形图上该节点的位置(对于进一步的绘图目的)。 所以,假设我的数据看起来像这样:

> Ltrs <- data.frame("A" = c(3,1), "B" = c(1,1), "C" = c(2,4), "D" = c(6,6))
> dend <- as.dendrogram(hclust(dist(t(Ltrs))))
> plot(dend)

The dendrogram

现在我可以提取分割/节点的位置:

> library(dendextend)
> nodes <- get_nodes_xy(dend)
> nodes <- nodes[nodes[,2] != 0, ]
> nodes
      [,1]     [,2]
[1,] 1.875 7.071068
[2,] 2.750 3.162278
[3,] 3.500 2.000000

现在我想获取节点下的所有标签,每个节点(来自'nodes'变量的行)。

这应该是这样的:

$`1`
[1] "D" "C" "B" "A"

$`2`
[1] "C" "B" "A"

$`3 `
[1] "B" "A"

有人可以帮帮我吗?在此先感谢:)

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

library(tidyverse)
library(dendextend)
Ltrs <- data.frame("A" = c(3,1), "B" = c(1,1), "C" = c(2,4), "D" = c(6,6))
dend <- as.dendrogram(hclust(dist(t(Ltrs))))

accumulator <- list();
myleaves <- function(anode){
    if(!is.list(anode))return(attr(anode,"label"))
    accumulator[[length(accumulator)+1]] <<- (reduce(lapply(anode,myleaves),c))
}

myleaves(dend);
ret <- rev(accumulator); #generation was depth first, so root was found last.

更好地测试一下。我不是很值得信赖。特别是,我真的希望列表ret处于有意义的顺序,否则将条目与正确的节点相关联会很痛苦!祝你好运。