I have a sf_network
object where I would like to sum all values from each edge such that the root edge would be equal to the sum of all the others. I’ve made a simple example for testing purposes below. I am working with igraph
and tidygraph
and would prefer a solution that uses them.
#Testing Data
tree_t<-create_tree(20, 3) |>
mutate(leaf = node_is_leaf())
iris_tree <- tree_t %>%
morph(to_linegraph) %>% #Morphing to convert edges to nodes
activate(nodes) %>%
mutate(value_2_sum = 1) |>
mutate(summed_value = map_bfs_back_dbl(node_is_root(), .f = function(node, path, ...) {
nodes <- .N()
if (is.null(nodes$leaf[node])) return(sum(nodes[path$node,]$value_2_sum,nodes$value_2_sum[node],na.rm = T))
return(sum(path$result[[1]],nodes$value_2_sum[node],na.rm=T)) #Problem with the logic here I think.
})) |>
unmorph()
#Plot
ggraph(iris_tree) +
geom_edge_diagonal2(aes(colour = summed_value, label = summed_value)) +
theme_graph()
It should be obvious but as you can see in the plot although most edges have their values correctly added but the first 4 on the top left of the chart is not catching the values from below. It seems to be an issue with the second return
call. The path$results
call I think is the issue but I am not sure. Any thoughts are welcome.