Question
Adding edge weights to igraph from an adjacency matrix
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.
2 98
2