1

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.

schnee
  • 1,050
  • 2
  • 9
  • 20
  • 2
    Please [see here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on how to post an R question that is easy to answer. This includes a sample of your data and all code needed to reproduce the issue. Specifically, it's unclear what packages you're working with – camille Jun 13 '18 at 16:18
  • edited with @camille's suggestion on package. – schnee Jun 13 '18 at 18:41
  • Your "_This is what I wound up doing_" code didn't work for me. I had to split it before the join. – ap53 Jun 20 '18 at 13:16

1 Answers1

1

I took a stab at a "tidygraph" way of doing things here. The main function is this one for calculating the variance of the value column:

calc_child_stats <- function(neighborhood, ...){
  ## By default the neighborhood includes the parent and all of it's children
  ## First remove the parent, then run analysis
  neighborhood %>% activate(nodes) %>% 
    slice(-1) %>% 
    select(value) %>% 
    pull %>% 
    var
}

Once you have that function, then it's a simple call to map_local instead of the map_bfs as you were trying:

tree <- create_tree(40, children = 3, directed = TRUE) %>%
  mutate(value = round(runif(40)*100))

tree %>% mutate(var = map_local_dbl(order = 1, mode="out", .f = calc_child_stats))
#> # A tbl_graph: 40 nodes and 39 edges
#> #
#> # A rooted tree
#> #
#> # Node Data: 40 x 2 (active)
#>   value   var
#>   <dbl> <dbl>
#> 1    29  34.3
#> 2    45 433  
#> 3    56 225. 
#> 4    47 868  
#> 5    78 604. 
#> 6    43 283  
#> # ... with 34 more rows
#> #
#> # Edge Data: 39 x 2
#>    from    to
#>   <int> <int>
#> 1     1     2
#> 2     1     3
#> 3     1     4
#> # ... with 36 more rows

While my tidygraph version is more "graphy" it doesn't seem very speedy, so I created a quick microbenchmarking test between the two methods:

library(microbenchmark)
microbenchmark(tree %>% mutate(var = map_local_dbl(order = 1, mode="out", .f = calc_child_stats)))
#> Unit: milliseconds
#>                                                                                       expr
#>  tree %>% mutate(var = map_local_dbl(order = 1, mode = "out",      .f = calc_child_stats))
#>       min       lq     mean   median      uq      max neval
#>  115.3325 123.0303 127.7889 126.6683 130.057 191.6065   100
microbenchmark(calc_child_stats_dplyr(tree))
#> Unit: milliseconds
#>                          expr      min       lq     mean   median       uq
#>  calc_child_stats_dplyr(tree) 4.915917 5.213939 6.292579 5.573978 6.717745
#>       max neval
#>  16.72846   100

Created on 2018-06-15 by the reprex package (v0.2.0).

Sure enough, the dplyr way is much speedier, so I would stick with that for now. They both gave the same values in my test.

For completeness, this was the fxn I used replicating the op method:

calc_child_stats_dplyr <- function(tree){
  tree <- tree %>%
    mutate(parent = bfs_parent(),
           name = row_number())

  tree %>% 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")
    )
}
sjfox
  • 112
  • 2
  • 10