Home > Enterprise >  Matching edges in 2 graphs
Matching edges in 2 graphs

Time:01-31

I have 2 graphs, lets call them g1 and g2. The graph g2 has the same structure as g1 but contains new edges that are not present in g1. I have to find these edges.

g1 <- graph(edges=c(1,2,2,3,1,3,3,4,2,4,1,5), n=5, directed=FALSE)
g2 <- graph(edges=c(1,2,2,3,1,3,3,4,2,4,1,5,3,5), n=5, directed=FALSE)

In this case what i'm looking for is the edge 3--5.

So far i thought of using the complementer of g1 then matching it with the edges from g2 to find these new edges. The problem is that i'm having trouble with the syntax. (new to R)

g1_complement <- complementer(g1)

Now i'd like to get only the new edges that are in g2 but NOT in g1. I was thinking of doing this.

E(g1_complement)[E(g1_complement) %in% E(g2)]

I was expecting to get only the new edges, but this returns all the g1_complement edges. I am only using igraph as library.

CodePudding user response:

Please find below one possible solution using the difference() function from the igraph library.

Reprex

library(igraph)

g1 <- graph(edges=c(1,2,2,3,1,3,3,4,2,4,1,5), n=5, directed=FALSE)
g2 <- graph(edges=c(1,2,2,3,1,3,3,4,2,4,1,5,3,5), n=5, directed=FALSE)


difference(g2, g1)
#> IGRAPH 9fb5e8c U--- 5 1 -- 
#>   edge from 9fb5e8c:
#> [1] 3--5

Created on 2022-01-30 by the reprex package (v2.0.1)

CodePudding user response:

We can try

> E(g2)[!E(g2) %in% E(g1)]
  1/7 edge from 9fdc2d2:
[1] 3--5

> E(g2)[setdiff(E(g2), E(g1))]
  1/7 edge from 9fdc2d2:
[1] 3--5
  •  Tags:  
  • Related