I'm struggling to figure out how to collapse 2 edges between the same 2 nodes into 1 and then calculate the sum of these edges.
I believe there's a way of doing it in igraph:
simplify(gcon, edge.attr.comb = list(weight = "sum", function(x)length(x)))
but I'd like to do it with tidygraph if possible as I've had success in implementing up to this point with tidygraph and I'm much more familiar with the tidyverse way of working.
My data looks like this:
from to Strength Dataframe Question Topic
1 0 32 4 weekly 1 Connection Frequency
2 0 19 5 weekly 1 Connection Frequency
3 0 8 3 weekly 1 Connection Frequency
4 0 6 5 weekly 1 Connection Frequency
5 0 2 4 weekly 1 Connection Frequency
6 0 14 5 weekly 1 Connection Frequency
With both 'from' and 'to' containing the same id's (e.g. from-to; 0-1 & 1-0). I'd like to condense so that only one iteration of the 0-1 relationship exists, with a summed Strength calculated.
Here's my code thus far:
graph <- data %>%
filter(Dataframe == "weekly" & Question == 1) %>%
as_tbl_graph(directed = FALSE) %>%
activate(edges) %>% # first manipulate edges
filter(!edge_is_loop()) %>% # remove any loops
activate(nodes) %>% # now manipulate nodes
left_join(node.group, by = "name") %>%
mutate(
Popularity = centrality_degree(mode = 'in'),
Centre = node_is_center(),
Keyplayer = node_is_keyplayer(k = 5))
Is it possible to merge the two corresponding edges into a single edge? I've searched the forum but have only come across references where the same nodes are repeated in the same columns (i.e. 0-1's across multiple rows).
library(tidygraph) # v1.2.0
library(dplyr) # v0.8.5
library(purrr) # v0.3.4
dat <- data.frame(
from = c("a", "a", "b", "c"),
to = c("b", "b", "a", "b"),
n = 1:4
)
Call to_simple() within convert() to collapse parallel edges. The corresponding edges and weights are stored in .orig_data as a list of tibbles. Then, extract the sum of the weight of collapsed edges from .orig_data.
dat %>%
as_tbl_graph() %>%
convert(to_simple) %>%
activate(edges) %>%
mutate(n_sum = map_dbl(.orig_data, ~ sum(.x$n)))
# A tbl_graph: 3 nodes and 3 edges
#
# A directed simple graph with 1 component
#
# Edge Data: 3 x 5 (active)
from to .tidygraph_edge_index .orig_data n_sum
<int> <int> <list> <list> <dbl>
1 1 2 <int [2]> <tibble [2 x 3]> 3
2 2 1 <int [1]> <tibble [1 x 3]> 3
3 3 2 <int [1]> <tibble [1 x 3]> 4
#
# Node Data: 3 x 2
name .tidygraph_node_index
<chr> <int>
1 a 1
2 b 2
3 c 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With