dataframe / edgelist to adjacency matrix

I am trying to convert an 3-column edgelist / df to adjacency matrix. I've tried to convert it to a weighted graph igraph and then get the matrix using: get.adjacency() but it returns wrong weights!

head(df)
from      to      weight
5001600 5001600   0.00
5001600 5001900   2.96
5001600 5002000   0.43
5001600 5002300   3.61
5001600 5002400   0.70
.          .       .
.          .       .
.          .       .
1 Like

Hello,

An adjacency matrix will only return a 0 or 1 indicating whether a given node is directly connected (1) or not (0) to another one. Depending on whether the graph is directed or undirected, the results may differ.

library(igraph)

#DATA
df = data.frame(
  from  = 5001600,
  to = c(5001600, 5001900, 5002000, 5002300, 5002400),
  weight = c(0, 2.96, 0.43, 3.61, 0.7)
)

# Undirected Graph
graph = graph_from_data_frame(df, directed = F)

#Adjacency
as_adjacency_matrix (graph, sparse = F)
#>         5001600 5001900 5002000 5002300 5002400
#> 5001600       1       1       1       1       1
#> 5001900       1       0       0       0       0
#> 5002000       1       0       0       0       0
#> 5002300       1       0       0       0       0
#> 5002400       1       0       0       0       0

# Directed Graph
graph = graph_from_data_frame(df, directed = T)

#Adjacency
as_adjacency_matrix (graph, sparse = F)
#>         5001600 5001900 5002000 5002300 5002400
#> 5001600       1       1       1       1       1
#> 5001900       0       0       0       0       0
#> 5002000       0       0       0       0       0
#> 5002300       0       0       0       0       0
#> 5002400       0       0       0       0       0

Created on 2022-03-31 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.