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

时间:2019-04-04 17:46:46

标签: 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,]

el看起来如下

    acotr1 actor2 actor1sendsActor2 actor2sendsActor1
[1,] "1"    "2"    "5.5"             "6.5"            
[2,] "1"    "3"    "3.5"             "1"              
[3,] "4"    "1"    "1.5"             "0"

使用可以轻松实现创建二进制边缘列表

 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  .    .    .

1 个答案:

答案 0 :(得分:1)

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

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
相关问题