using the tidygraph package in R, given a tree, I'd like to calculate the mean, sum, variance... of a value for each of the direct children of each node in the tree.
My intuition is to use map_bfs_back_dbl or related and have tried modifying the help example, but am stuck
library(tidygraph)
# Collect values from children
create_tree(40, children = 3, directed = TRUE) %>%
  mutate(value = round(runif(40)*100)) %>%
  mutate(child_acc = map_bfs_back_dbl(node_is_root(), .f = function(node, path, ...) {
    if (nrow(path) == 0) .N()$value[node]
    else {
      sum(unlist(path$result[path$parent == node]))
    }
  }))
For the above, I'd like the mean value for all direct, first-level, children of each parent in the tree.
Update:: I've tried this approach (which calculate the variance of the child attribute):
library(tidygraph)
create_tree(40, children = 3, directed = TRUE) %>%
  mutate(parent = bfs_parent(),
         value = round(runif(40)*100)) %>% 
  group_by(parent) %>%
  mutate(var = var(value))
Which is darn close:
# Node Data: 40 x 3 (active)
# Groups:    parent [14]
  parent value   var
*  <int> <dbl> <dbl>
1     NA  2.00    NA
2      1 13.0   1393
3      1 63.0   1393
4      1 86.0   1393
5      2 27.0    890
6      2 76.0    890
# ... with 34 more rows
What I'd like to see is something like:
# Node Data: 40 x 3 (active)
# Groups:    parent [14]
  parent value   var  child_var
*  <int> <dbl> <dbl>      <dbl>
1     NA  2.00    NA       1393
2      1 13.0   1393        890 
3      1 63.0   1393       (etc)
4      1 86.0   1393
5      2 27.0    890
6      2 76.0    890
# ... with 34 more rows
Which moves the (first) "var" value up to the node identified by the "parent" value. Help? Suggestions?
Edit: This is what I wound up doing:
tree <- create_tree(40, children = 3, directed = TRUE) %>%
  mutate(parent = bfs_parent(),
         value = round(runif(40) * 100),
         name = row_number()) %>%
  activate(nodes) %>%
  left_join(
    tree %>%
      group_by(parent) %>%
      mutate(var = var(value)) %>% activate(nodes) %>% as_tibble() %>%
      group_by(parent) %>% summarize(child_stat = first(var)),
    by=c("name" = "parent")
  )
Feels not-very-tidygraph, but seems to work. Open to optimizations.
 
    