title: Aggregating multiple variables on a data tree with R
body: <p>I am currently trying to build trees for each of my sample in a metagenomic context.</p>
  
  <p>Here is an example dataset :</p>
  
  <pre><code>library(phyloseq)
  library(dplyr)
  data(GlobalPatterns)
  
  mydata &lt;- merge(GlobalPatterns@tax_table, GlobalPatterns@otu_table, by = "row.names")
  mydata &lt;- mydata %&gt;% dplyr::select(-one_of("Row.names"))
  mydata$pathString &lt;- apply(mydata[,1:7], 1, paste, collapse="/")
  tree &lt;- data.tree::as.Node(mydata)
  </code></pre>
  
  <p>The thing is now to aggregate the value at each taxonomic level. Indeed, if I take the values for one sample, they are all at NA exept for the lowest taxonomic level (species) :</p>
  
  <pre><code>print(tree, "CL3")
  </code></pre>
  
  <p>I used the idea proposed in here : <a href="https://stackoverflow.com/questions/45225671/aggregating-values-on-a-data-tree-with-r">Aggregating values on a data tree with R</a> to perform the aggregation, which is working sample by sample : </p>
  
  <pre><code>myApply &lt;- function(node) {
    node$CL3_2 &lt;- sum(c(node$CL3, purrr::map_dbl(node$children, myApply)), na.rm = TRUE)
  }
  
  myApply(tree)
  print(tree, "CL3_2")
  </code></pre>
  
  <p>The idea for me would be to create a function that works for a vector n of samples and that perfom the aggregation. I tried to change the function by adding a "sample" parameter but with no success</p>
  
  <pre><code># does not work
  myApply &lt;- function(node, sample) {
    new_sample &lt;- paste0("new_", sample)
    node$new_sample &lt;- sum(c(node$sample, purrr::map_dbl(node$children, myApply)), na.rm = TRUE)
  }
  </code></pre>