Search code examples
rbreadth-first-searchdendrogram

Getting a dendrogram's branch lengths in a breadth-first-search order


Is there any R function to retrieve the branch lengths of a dendrogram:

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

in a breadth-first-search order?

For dend I'd like to get this result:

c(16.38688,15.41441,15.99504,14.68365,13.52949,14.39275,12.96921,13.91157,13.15395)

which is node depths (excluding leaves) ordered by bps.

Thanks


Solution

  • The data:

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

    Using the data.tree package allows traversing trees in various orders. level will give what the question specifies:

    require(data.tree)
    dend.dt <- as.Node(dend)
    sapply(Traverse(dend.dt,traversal = "level", pruneFun = isNotLeaf),function(x) x$plotHeight)
    [1] 16.38688 15.41441 15.99504 14.68365 13.52949 14.39275 12.96921 13.91157 13.15395