I'm trying to tally up the hours from a data tree structure. I can add up the hours directly under parent node, but I can't include the hours assigned to the parent nodes in the tree. Any suggestions would be great.
This is what I am getting:
levelName hours totalhours
1 Ned NA 1
2 °--John 1 3
3 °--Kate 1 3
4 ¦--Dan 1 1
5 ¦--Ron 1 1
6 °--Sienna 1 1
This is what I'm looking for:
levelName hours totalHours
1 Ned NA 5
2 °--John 1 5
3 °--Kate 1 4
4 ¦--Dan 1 1
5 ¦--Ron 1 1
6 °--Sienna 1 1
Here's my code:
# Install package
install.packages('data.tree')
library(data.tree)
# Create data frame
to <- c("Ned", "John", "Kate", "Kate", "Kate")
from <- c("John", "Kate", "Dan", "Ron", "Sienna")
hours <- c(1,1,1,1,1)
df <- data.frame(from,to,hours)
# Create data tree
tree <- FromDataFrameNetwork(df)
print(tree, "hours")
# Get running total of hours that includes all nodes and children values.
tree$Do(function(x) x$total <- Aggregate(x, "hours", sum), traversal = "post-order")
print(tree, "hours", runningtotal = tree$Get(Aggregate, "total", sum))