给定一个单分 igraph 对象
G
和一个邻接矩阵 attrib
,仅包含 G
中的部分边的边属性 ,将属性添加到 G
的最有效方法是什么。
这是一个可重现的示例:
> 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
一种可能性是使
attrib
成为边缘列表,然后将它们在循环中一一添加。但是,我想一定有更好的选择。感谢您的任何想法。
输入数据
set.seed(5)
library(igraph)
n <- 10
G <- erdos.renyi.game(n, .5, type="gnp")
G <- simplify(G, remove.multiple = TRUE, remove.loops = TRUE)
attrib <- as_adjacency_matrix(G, sparse = FALSE)
attrib[attrib == 1] <- sample(c(0, 1),sum(attrib),replace = TRUE)
attrib #Adjacency matrix containing attributes
在稀疏矩阵表示中使用三元组的解决方案
# Using the Matrix package.
# Create symmetric sparse matrix (M).
# Create vertex sequence (vp), x1, y1, x2, y2, ...
# Create a list of values (M@x)
library(Matrix)
M <- as(attrib, "TsparseMatrix")
vp <- c(rbind(M@i, M@j)) + 1
# Convert vertex sequence to edge ids.
# Set edge attributes by edge id.
eids <- get.edge.ids(G, vp, directed=FALSE)
g2 <- set_edge_attr(G, "weight", index = eids, value=M@x)
# Show edges without weight.
E(g2)[which(is.na(E(g2)$weight))]
# + 5/23 edges from ad6a11e:
# [1] 1-- 7 4--10 5-- 6 6--10 7-- 9
g3 <- set_edge_attr(g2, name = "label", value = E(g2)$weight)
plot(g3)