Maksym Moroz
Maksym Moroz

Reputation: 316

Extract a list of edges between community nodes and other nodes for each community

Suppose we have a simple weighted network on which we perform some sort of community detection. Next we extract particular community and the final task is to extract all edges between nodes of this community and all other nodes.

Below I pasted the toy code.

# Create toy graph
library(igraph)
set.seed(12345)
g <- make_graph("Zachary")
# Add weights to edges
E(g)$weight <- sample(x = 1:10, size = ecount(g), replace = TRUE)
# Run community detection
cl <- cluster_louvain(g)

There are 5 nodes which belong to community #1, 12 nodes which belong to community #2, etc.

> table(membership(cl))
 1  2  3  4 
 5 12  2 15

Now we extract community #1:

g1 <- induced_subgraph(g, which(cl$membership == 1))

Question: how to find edges which connect nodes in community #1 with all other nodes (excluding edges which define community #1)?

There is an answer related to certain community below

You start by getting all edges based in your community:

all_edges <- E(g)[inc(V(g)[membership(cl) == 1])]
all_edges
+ 10/78 edges:
 [1] 1-- 5 1-- 6 1-- 7 1--11 5-- 7 5--11 6-- 7 6--11 6--17 7--17

Then, filter out the ones that are completely internal (both vertices are in the community):

all_edges_m <- get.edges(g, all_edges) #matrix representation

all_edges[!(
 all_edges_m[, 1] %in% V(g)[membership(cl) == 1] & 
   all_edges_m[, 2] %in% V(g)[membership(cl) == 1]
 )] # filter where in col1 and col2
+ 4/78 edges:
[1] 1-- 5 1-- 6 1-- 7 1--11

But for me its necessary to get the whole list containing those nodes for each community. not only for the one. Are the any suggestions to create this loop? It would be superb if yes :)

Upvotes: 3

Views: 1275

Answers (1)

Ben Nutzer
Ben Nutzer

Reputation: 1163

Here is my take on your problem:

library(igraph) 
set.seed(12345)
g <- make_graph("Zachary")
E(g)$weight <- sample(x = 1:10, size = ecount(g), replace = TRUE)
cl <- cluster_louvain(g)

add membership as a vertex attribute

V(g)$name <- membership(cl)

get edgelist

x <- as_edgelist(g, names = T)

here are all edges that connect vertices of different communities

V(g)$name <- 1:vcount(g)
E(g)[x[,1] != x[,2]]

optional check

 E(g)$color <- ifelse(x[,1] != x[,2], "red", "blue")
 plot(g, edge.color = E(g)$color)
 plot(cl, g)

Upvotes: 3

Related Questions