如何将加权边列表转换为R中的邻接矩阵

如何将加权边列表转换为R中的邻接矩阵,r,igraph,R,Igraph,我想将一个加权的有向边列表转换为一个邻接矩阵,其中包含不同单元格中发送方和接收方的权重。我如何才能最有效地做到这一点 以下是一个例子: el <- rbind(c("acotr1", "actor2", "actor1sendsActor2", "actor2sendsActor1"), c(1,2,5.5,6.5), c(1,3, 3.5, 1), c(4,1,1.5,0)) colnames(el) <- el[1,] el <- el[-1,] 通过使用 as

我想将一个加权的有向边列表转换为一个邻接矩阵,其中包含不同单元格中发送方和接收方的权重。我如何才能最有效地做到这一点

以下是一个例子:

 el <- rbind(c("acotr1", "actor2", "actor1sendsActor2", "actor2sendsActor1"), c(1,2,5.5,6.5), c(1,3, 3.5, 1),  c(4,1,1.5,0))
 colnames(el) <- el[1,]
 el <- el[-1,]
通过使用

 as.matrix(table(el[,1], el[,2]))
其中,
el[,1],el[,2]
是网络中节点的名称

但是我想要

  1    2    3    4
1 .    5.5  3.5  0
2 6.5  .    .    .
3 1    .    .    .
4 1.5  .    .    .

首先,让我们将矩阵转换为数字矩阵:

mode(el) <- "numeric"
el
#      acotr1 actor2 actor1sendsActor2 actor2sendsActor1
# [1,]      1      2               5.5               6.5
# [2,]      1      3               3.5               1.0
# [3,]      4      1               1.5               0.0
模式(el)
mode(el) <- "numeric"
el
#      acotr1 actor2 actor1sendsActor2 actor2sendsActor1
# [1,]      1      2               5.5               6.5
# [2,]      1      3               3.5               1.0
# [3,]      4      1               1.5               0.0
# Creating an adjacency matrix of zeros for 1, ..., max(agents)
M <- matrix(0, max(el[, 1:2]), max(el[, 1:2]))
# Using the 3rd column
M[el[, 1:2]] <- el[, 3]
# Using the 4th column
M[el[, 2:1]] <- el[, 4]
M
#      [,1] [,2] [,3] [,4]
# [1,]  0.0  5.5  3.5    0
# [2,]  6.5  0.0  0.0    0
# [3,]  1.0  0.0  0.0    0
# [4,]  1.5  0.0  0.0    0