简体   繁体   中英

How to label each node in a dendrogram based on label for the children using R

I have a dendrogram in R where each leaf has a value. I like to define each node's value by summing the value of its children. I am familiar with dendrapply, however I don't know how to access a node's child in the function and how to write the function recursively.

here is the code to begin with:

library("stats")
library("fastcluster")
library("cluster")
D = rbind( + c(1,1,1,1,1), 
 + c(1,2,1,1,1),
 + c(2,2,2,2,2), 
 + c(3,4,5,6,9)

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

apply_text <<- function(n) {
   if (!is.leaf(n)) {

      attr(n, "edgetext") <- add the value of the branches
   }
   if (is.leaf(n)) {
      attr(n, "edgetext") <- 1
   }
   n
}

tmp <- dendrapply(dnd, apply_text)
plot(tmp)

This may be an answer, however, it is reimplementing the dendrapply.

apply_text <<- function(n){
  if (!is.leaf(n)) {
    cutversion = cut(n, h = attributes(n)$height)
    leftLabel = attr(apply_text(cutversion$lower[[1]]), "edgetext")  
    rightLabel= attr(apply_text(cutversion$lower[[2]]), "edgetext")
    attr(n, "edgetext") = as.numeric(as.character(leftLabel)) + as.numeric(as.character(rightLabel)) 
     }
  if(is.leaf(n)) {
    attr(n,"edgetext") <- 1
  }
    n
}

tmp <- dendrapply(dnd, apply_text)

Does anybody have a clue how to remove the polygon on the labels? Somebody else also seems to have asked for them to be removed. Any progress on that?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM