How to compare two graphs to Identify number of same/different edges between two graph using igraph R package

Viewed 680

I have two undirected graphs

library(igraph)
g1 <- make_graph( edges=c("A", "B", "B", "C", "C", "A"), directed=F ) 

g2 <- make_graph( edges=c("A", "B", "B", "C", "A", "C", "C", "D"), directed=F ) 

I want to compare the edges of g1 to g2 graphs. I want to count the number of edges that are exactly the same, as well as the number of edges that are reversed (e.g. A->C changes to C->A as in undirected network both imply as similar edge), and the number of additional edges.

Is there a simple function for doing this sort of comparison of edges? Could anyone please help me to solve this.

2 Answers

You can use graph.intersection

> graph.intersection(g1,g2)
IGRAPH aadee49 UN-- 4 3 --
+ attr: name (v/c)
+ edges from aadee49 (vertex names):
[1] B--C A--C A--B

Or, I guess you can use as_data_frame + intersect to see the common edges

commEdges <- intersect(as_data_frame(g1),as_data_frame(g2))

which gives

  from to
1    A  B
2    B  C
3    A  C

and the number of common edges can be counted by nrow(commEdges)


If you just want to know how many common edges, a simple way is

> length(intersect(E(g1),E(g2)))
[1] 3
g1 <- make_graph(edges=c("A", "B",
                         "B", "C",
                         "C", "A"),
                 directed=F) 
g2 <- make_graph(edges=c("A", "B",
                         "B", "C",
                         "A", "C",
                         "C", "D"),
                 directed=F)
E(g1 %s% g2)

Gives:

+ 3/3 edges from 43be050 (vertex names):
[1] B--C A--C A--B
Related