Reputation: 353
I would like to transform a weighted, directed edge list into an adjacency matrix with the weights for the sender and receiver in different cells. How can I do this most efficiently?
here is an example:
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 looks as follows
acotr1 actor2 actor1sendsActor2 actor2sendsActor1
[1,] "1" "2" "5.5" "6.5"
[2,] "1" "3" "3.5" "1"
[3,] "4" "1" "1.5" "0"
Creating a binary edge list can be easily achieved by using
as.matrix(table(el[,1], el[,2]))
where el[,1], el[,2]
are the names of the nodes in the network.
but I would like to have
1 2 3 4
1 . 5.5 3.5 0
2 6.5 . . .
3 1 . . .
4 1.5 . . .
Upvotes: 1
Views: 591
Reputation: 48191
First let's convert the matrix to a numeric one:
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
I don't think there's a magic shortcut for weighted (especially with two columns) cases, but the following is also succinct:
# 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
Upvotes: 1