0
votes

I would like to pass igraph a matrix of a series of edges for it to form between nodes. The edges are undirected. However, it is not adding the edges I would like for it to add

my graph looks like this

mygraph
IGRAPH U--- 30 11 -- 
+ attr: color (v/c), color (e/c)
+ edges:
[1]  3-- 4  3-- 9  4-- 5  4-- 6  6--10 12--14 15--20 16--21 25--27 25--30 26--29

I now want to add these undirected edges (edges in m go horizontally e.g. 12--13 is an edge, 9--13 is an edge, etc). If the edges are repeating they should be removed since it is undirected (meaning 23--20 is the same as 20--23).

m
     value L1
[1,]     6  2
[2,]     4  5
[3,]     6  5
[4,]     2  6
[5,]    12 13
[6,]     9 13
[7,]    23 20
[8,]    20 23

when I do

add_edges(mygraph, m)

I get the following (note, the total number of edges is correct, but not the nodes that should have edges. For example, 12--13 does not exist and instead 12--9 is formed, which was not specified in m). It seems like add_edges is adding an edge vertically to make 12--9 instead of horizontally to make 12--13 from m

IGRAPH U--- 30 19 -- 
+ attr: color (v/c), color (e/c)
+ edges:
[1]  3-- 4  3-- 9  4-- 5  4-- 6  6--10 12--14 15--20 16--21 25--27 25--30 26--29  4-- 6  2-- 6  9--12 20--23  2-- 5  5-- 6 13--13
[19] 20--23

how can edges be added horizontally from a matrix to a graph using igraph?

1

1 Answers

1
votes

You need to make a transpose of your edge matrix before adding them to your graph, the reason is that data in a matrix is stored by column, and it seems that igraph does not provide a proper interface for matrix, i.e, it doesn't interpret your matrix as by row edge matrix but just a vector and interpret each adjacent pair as a new edge:

Take a look at this simple example:

library(igraph)
mygraph <- graph(c(1,2,3,4,5,6))
mygraph
IGRAPH D--- 6 3 -- 
+ edges:
[1] 1->2 3->4 5->6

m <- matrix(c(6,2,4,5), byrow = TRUE, ncol = 2)
m
     [,1] [,2]
[1,]    6    2
[2,]    4    5

If I add m directly to the graph object:

add_edges(mygraph, m)
IGRAPH D--- 6 5 -- 
+ edges:
[1] 1->2 3->4 5->6 6->4 2->5

I have 6 -> 4 and 2 -> 5 added as graph, which is because:

as.vector(m)
# [1] 6 4 2 5

So adjacent nodes are interpreted as edges. But if you transpose m before adding it as edges, it gives the correct result.

add_edges(mygraph, t(m))
IGRAPH D--- 6 5 -- 
+ edges:
[1] 1->2 3->4 5->6 6->2 4->5