2

I would like to either:

  1. remove a subtree and then merge a new subtree to the original dendrogram so that it is in the same position as the one removed.
  2. or replace a subtree with another one.

I know that merge() can merge two dendrograms at the top. Does it also merge it at a specified node. If so how? If not, is there another method that would do that?

I know that cut() cuts the dendrogram at a certain height or into a specific number of node. But how do I make it remove only a specific subtree?

The specification of a subtree would be the attribute of the first node in it. eg attr(n,"attribute")== something, which can be done through dendrapply().


Here's a sample code of how the dendrograms are made.

library("stats")
library("fastcluster")

x=matrix(c(1:20),ncol=4)
y=matrix(c(21:40),ncol=4)

#creating hclusters
xcl=hclust.vector(x)
ycl=hclust.vector(y)

#converting to dendrograms
xdend=as.dendrogram(xcl)
ydend=as.dendrogram(ycl)

# merging two dendrograms at the top
zdend=merge(xdend,ydend)

- Note: I found out how to replace a subtree by the following.

 merging <- function(n,subtree){
    if (attr(n,"members")==2){
    treeMerged2<<- merge(n,subtree)}}


     D=rbind(
    + c(1,1,1,1,1),
    + c(1,2,1,1,1),
    + c(2,2,2,2,2),
    + c(2,2,2,2,1),
    + c(3,3,3,3,3),
    + c(3,3,3,3,2))

Ddend=as.dendrogram(hclust.vector(D))

    tr=dendrapply(Ddend,merging, xdend)

Problem:

1) it replaces its sister subtree instead of the one desired.

2) the original tree doesn't get change.

3) the new tree "treeMerged2" that is created only has the added subtree and the sister subtree, not the rest of the tree.

Question:

  • How do I make the output be the original tree with the new subtree in it?

Thanks.

Tal Galili
  • 24,605
  • 44
  • 129
  • 187
user1562626
  • 125
  • 1
  • 7

1 Answers1

0

You could use the prune function in the dendextend package, designed exactly for this sort of thing. (look at ?prune). Once pruned, you can use the merge function.

If you need to replace a tree in a specific sub part of the tree, I believe that this is not currently possible using a general purpose function. You could manually add the subtree by using nestes [[ ]], but notice that the attributes you will get will no longer be correct (especially number of members, and maybe also height). So you would need to think this more seriously in order to resolve this generally (if you get to solve it, feel invited to commit a patch to dendextend, or just e-mail me about it: tal.galili@gmail.com)

Tal Galili
  • 24,605
  • 44
  • 129
  • 187