You can simply use the recursive function:
myApply <- function(node) {
node$totalHours <-
sum(c(node$hours, purrr::map_dbl(node$children, myApply)), na.rm = TRUE)
}
myApply(tree)
print(tree, "hours", "totalHours")
Result:
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
Edit: Filling two elements:
to <- c("Ned", "John", "Kate", "Kate", "Kate")
from <- c("John", "Kate", "Dan", "Ron", "Sienna")
hours <- c(1,1,1,1,1)
hours2 <- 5:1
df <- data.frame(from,to,hours, hours2)
tree <- FromDataFrameNetwork(df)
print(tree, "hours", "hours2")
myApply <- function(node) {
res.ch <- purrr::map(node$children, myApply)
a <- node$totalHours <-
sum(c(node$hours, purrr::map_dbl(res.ch, 1)), na.rm = TRUE)
b <- node$totalHours2 <-
sum(c(node$hours2, purrr::map_dbl(res.ch, 2)), na.rm = TRUE)
list(a, b)
}
myApply(tree)
print(tree, "hours", "totalHours", "hours2", "totalHours2")
Result:
levelName hours totalHours hours2 totalHours2
1 Ned NA 5 NA 15
2 °--John 1 5 5 15
3 °--Kate 1 4 4 10
4 ¦--Dan 1 1 3 3
5 ¦--Ron 1 1 2 2
6 °--Sienna 1 1 1 1