I need to reshape a two column matrix into a matrix that is similar to an adjacency matrix. I have the following dataset:
firm_id_1 firm_id_2
1 2
1 4
1 5
2 1
2 3
3 2
3 6
4 1
4 5
5 4
6 3
and so on... for 4000 different firm_id
.
In the first column, there is a direct link between firm_id_1
and firm_id_2
. For instance, firm_id
= 1 is directly linked (first degree) to firm_id
2, 4, 5, indirectly linked (to a second degree) to 3 via firm_id
=2, and indirectly linked to a third degree to firm_id
=6 via firm_id
=3, and so on...
I would like to build this matrix in R:
firm_id [1] [2] [3] [4] [5] [6]
[1] 1 2 1 1 3
[2] 1 1 2
[3] 1 1
[4] 1
[5] 1
[6] 1
Each number represents the degree of separation in the network. Is this doable in R?
library(igraph)
g <- graph.edgelist(mat)
shortest.paths(g)
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 0 1 2 1 1 3
# [2,] 1 0 1 2 2 2
# [3,] 2 1 0 3 3 1
# [4,] 1 2 3 0 1 4
# [5,] 1 2 3 1 0 4
# [6,] 3 2 1 4 4 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With