Andrej - 9 months ago 35

R Question

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`

`#2`

`> table(membership(cl))`

1 2 3 4

5 12 2 15

Now we extract community

`#1`

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

`#1`

Answer Source

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
```