title: How to label each node in a dendrogram based on label for the children using R
body: <p>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. </p>
  
  <p>here is the code to begin with:</p>
  
  <pre><code>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 &lt;&lt;- function(n) {
     if (!is.leaf(n)) {
  
        attr(n, "edgetext") &lt;- add the value of the branches
     }
     if (is.leaf(n)) {
        attr(n, "edgetext") &lt;- 1
     }
     n
  }
  
  tmp &lt;- dendrapply(dnd, apply_text)
  plot(tmp)
  </code></pre>