7
votes

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?

2
What code are you using to "create the matrix" and "plot the graph"? To me it seems that your CSV has two columns and many rows, which when read into a table/matrix of course is not square? - mathematical.coffee
That's right...it does have 2 columns and many rows...is there a way that i can create an adjacency matrix using this data? I am trying to use the functions as.matrix and graph.adjacency. - user2203793

2 Answers

18
votes

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 . . . .
7
votes

Maybe something like:

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

x <- table(dat)
x %*% t(x)

But maybe you actually want: igraph::graph.data.frame