Explore Courses Blog Tutorials Interview Questions
0 votes
in R Programming by (50.2k points)

I am having an edge list and I just need to convert it into an adjacency matrix. Is there a simple code I can use to do this?

The data looks like this:

  From To    Weight

1    a  a 0.3274570

2    b  a 0.7188648

3    a  b 0.1097450

4    b  b 0.9054419

Here is the code, I have implemented:

edgelist <- setNames(cbind(expand.grid(letters[1:2], letters[1:2]), runif(4)), c("From", "To", "Weight"))


1 Answer

0 votes
by (108k points)

In your case what you can do is use the get.adjacency() from the igraph package in R programming.


mygraph <-

get.adjacency(mygraph, sparse = FALSE, attr='Weight')

#          a         b

#a 0.3274570 0.1097450

#b 0.7188648 0.9054419

You can simply transform the data to a matrix, it might be helpful to be prepared to use the rest of this package's features.

How to turn a weighted edgelist into an adjacency matrix in r
by (100 points)
What if my original df has no column names? How do I assign attr=<column 3>?

Update: NVM, with further poking turns out the "default" "name" is 'X3', so attr='X3' works.

Browse Categories