Given a unipartite igraph object G
and an adjacency matrix attrib
containing an edge attribute for only some of the edges in G
, what is the most efficient way to add the attributes to G
.
Here's a reproducible example:
> set.seed(5)
> library(igraph)
> G <- erdos.renyi.game(10,.5,type="gnp")
> as_adjacency_matrix(G) #Adjacency matrix for network
10 x 10 sparse Matrix of class "dgCMatrix"
[1,] . . . 1 1 . 1 1 1 1
[2,] . . . 1 . . . 1 . .
[3,] . . . 1 1 . 1 . 1 1
[4,] 1 1 1 . 1 1 . . 1 1
[5,] 1 . 1 1 . 1 . . . 1
[6,] . . . 1 1 . . . 1 1
[7,] 1 . 1 . . . . . 1 1
[8,] 1 1 . . . . . . . .
[9,] 1 . 1 1 . 1 1 . . .
[10,] 1 . 1 1 1 1 1 . . .
> attrib <- as_adjacency_matrix(G, sparse = FALSE)
> attrib[attrib==1] <- sample(c(0,1),sum(attrib),replace=TRUE)
> attrib #Adjacency matrix containing attributes
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 0 1 1 0 0 0 1 0
[2,] 0 0 0 0 0 0 0 1 0 0
[3,] 0 0 0 0 0 0 1 0 1 1
[4,] 0 1 1 0 1 1 0 0 0 0
[5,] 1 0 1 0 0 0 0 0 0 1
[6,] 0 0 0 1 0 0 0 0 1 0
[7,] 0 0 1 0 0 0 0 0 0 1
[8,] 1 0 0 0 0 0 0 0 0 0
[9,] 1 0 1 1 0 1 0 0 0 0
[10,] 1 0 0 0 0 0 1 0 0 0
One possibility is to make attrib
an edgelist, then add them one-by-one in a loop. But, I'm thinking there must be a better option. Thanks for any ideas.
I guess this should work for you
G <- G %>%
set_edge_attr("attrib", value = pmax(attrib,t(attrib))[as_edgelist(G)])
which gives
> G
IGRAPH c11c0d1 U--- 10 23 -- Erdos-Renyi (gnp) graph
+ attr: name (g/c), type (g/c), loops (g/l), p (g/n), attrib (e/n)
+ edges from c11c0d1:
[1] 1-- 4 2-- 4 3-- 4 1-- 5 3-- 5 4-- 5 4-- 6 5-- 6 1-- 7 3-- 7 1-- 8 2-- 8
[13] 1-- 9 3-- 9 4-- 9 6-- 9 7-- 9 1--10 3--10 4--10 5--10 6--10 7--10
> E(G)$attrib
[1] 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 1 1 0 1 0 1
and plot(G, edge.label = E(G)$attrib)
shows