title: Reducing the number of nodes of a tree, to obtain nodes with more than one child node
body: <p>The following tree:</p>
  
  <p><a href="https://i.stack.imgur.com/wpay6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wpay6.png" alt="enter image description here"></a></p>
  
  <p>has been obtained from the following matrix</p>
  
  <pre><code>&gt; mat
  7  23 47 41 31
  7  23 53 41 31
  7  23 53 41 37
  7  29 47 41 31
  7  29 47 41 37
  7  29 53 41 31
  7  29 53 41 37
  11 29 53 41 31
  11 29 53 41 37
  </code></pre>
  
  <p>taking each columns of 'mat' as a level of the tree. If 'data' is the dataframe where the matrix 'mat' is stored </p>
  
  <pre><code>V1 V2 V3 V4 V5
  7  23 47 41 31
  7  23 53 41 31
  7  23 53 41 37
  7  29 47 41 31
  7  29 47 41 37
  7  29 53 41 31
  7  29 53 41 37
  11 29 53 41 31
  11 29 53 41 37
  </code></pre>
  
  <p>the code that produces above tree is the following</p>
  
  <pre><code>&gt; data$pathString&lt;-paste("0", data$V1,data$V2,data$V3,data$V4,data$V5,sep = "/")
  &gt; p_tree &lt;- as.Node(data)
  &gt; export_graph(ToDiagrammeRGraph(p_tree), "tree.png")
  </code></pre>
  
  <p>I would like to modify the tree as follows: (1) if a node at level 'n', labelled by number x, has only one child node at level 'n+1', labelled by number y, then the program brings together these two nodes in one node labelled by the result of the product x*y; 2) if the node at level 'n+1' does not have child nodes, the program does nothing and starts again from another branch; 3) if the node at level 'n+1' has more than one child node, the program apply point (1) and starts again from each of child nodes.</p>
  
  <p>For example, for the tree of our example, the code should:</p>
  
  <ul>
  <li>replace the nodes circled in red with a node labelled by 31*41*47=59737</li>
  <li>replace the nodes circled in orange with a node labelled by 53*41=2173</li>
  <li>replace the nodes circled in green with a node labelled by 47*41=1927</li>
  <li>replace the nodes circled in blue with a node labelled by 11*29*53*41=693187</li>
  </ul>
  
  <p><a href="https://i.stack.imgur.com/ojSun.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ojSun.png" alt="enter image description here"></a></p>