title: Walking a hierarchical tree
body: <p>I want to be able to "walk" (iterate) through a hierarchical cluster (see figure below and code). What I want is:</p>
  
  <ol>
  <li><p>A function that that takes a matrix and a minimum height. Say 10 in this example.</p>
  
  <pre><code>splitme &lt;- function(matrix, minH){
      ##Some code
  }
  </code></pre></li>
  <li><p>Starting from the top to <code>minH</code>, start cutting whenever there is a new split. This is the first problem. How to detect a new splits to get an height <code>h</code>. </p></li>
  <li><p>At this particular <code>h</code>, how many clusters are there? Retrieve clusters</p>
  
  <pre><code>mycl &lt;- cutree(hr, h=x);#x is that found h
  count &lt;- count(mycl)# Bad code
  </code></pre></li>
  <li><p>Save in variable(s) each of the new matrices. This is another hard one, dynamic creation of x new matrices. So perhaps a function that takes the clusters does what needs to be done (comparisons) and returns a variable ??</p></li>
  <li><p>Continue 3 and 4 until <code>minH</code> reached</p></li>
  </ol>
  
  <h3>Figure</h3>
  
  <p><img src="https://i.stack.imgur.com/QNBE4.jpg" alt="enter image description here"></p>
  
  <h3>Code</h3>
  
  <pre><code># Generate data
  set.seed(12345)
  desc.1 &lt;- c(rnorm(10, 0, 1), rnorm(20, 10, 4))
  desc.2 &lt;- c(rnorm(5, 20, .5), rnorm(5, 5, 1.5), rnorm(20, 10, 2))
  desc.3 &lt;- c(rnorm(10, 3, .1), rnorm(15, 6, .2), rnorm(5, 5, .3))
  
  data &lt;- cbind(desc.1, desc.2, desc.3)
  
  # Create dendrogram
  d &lt;- dist(data) 
  hc &lt;- as.dendrogram(hclust(d))
  
  # Function to color branches
  colbranches &lt;- function(n, col)
    {
    a &lt;- attributes(n) # Find the attributes of current node
    # Color edges with requested color
    attr(n, "edgePar") &lt;- c(a$edgePar, list(col=col, lwd=2))
    n # Don't forget to return the node!
    }
  
  # Color the first sub-branch of the first branch in red,
  # the second sub-branch in orange and the second branch in blue
  hc[[1]][[1]] = dendrapply(hc[[1]][[1]], colbranches, "red")
  hc[[1]][[2]] = dendrapply(hc[[1]][[2]], colbranches, "orange")
  hc[[2]] = dendrapply(hc[[2]], colbranches, "blue")
  
  # Plot
  plot(hc)
  </code></pre>