Adjacency matrix in R

user2203793 picture user2203793 · Jan 29, 2014 · Viewed 30k times · Source

I want to find the adjacency matrix from a csv file that includes the information as follows:

A B 
1 2
1 3
1 4
2 5
3 7

and so on. There are 100 nodes but everytime I try to create a matrix and subsequently plot the graph, the error is that it is a non-square matrix. Can somebody help me with the correct code in R?

Answer

Brian Diggs picture Brian Diggs · Jan 29, 2014

What you have is an edge list. You can build a graph from that and then covert it to an adjacency matrix:

library(igraph)

dat <- read.table(text="A B 
1 2
1 3
1 4
2 5
3 7", header=TRUE)

get.adjacency(graph.edgelist(as.matrix(dat), directed=FALSE))

That gives

7 x 7 sparse Matrix of class "dgCMatrix"

[1,] . 1 1 1 . . .
[2,] 1 . . . 1 . .
[3,] 1 . . . . . 1
[4,] 1 . . . . . .
[5,] . 1 . . . . .
[6,] . . . . . . .
[7,] . . 1 . . . .