10

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?

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
user2203793
  • 135
  • 1
  • 2
  • 8
  • 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 Jan 29 '14 at 00:07
  • 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 Jan 29 '14 at 00:21

2 Answers2

22

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 . . . .
baxx
  • 3,956
  • 6
  • 37
  • 75
Brian Diggs
  • 57,757
  • 13
  • 166
  • 188
  • The problem is that I cannot input the data manually and the code does not work for a csv file. It again gives the same error - graph.edgelist expects a matrix with two columns. – user2203793 Jan 29 '14 at 01:00
  • 3
    @user2203793 -- Do you know how to read in tabular data from a csv, using e.g. `dat <- read.csv("path/to/file.csv", header=TRUE)`? Brian's answer works beautifully, but he's (quite reasonably) assuming you've at least got your data read into a two column data.frame... – Josh O'Brien Jan 29 '14 at 01:03
10

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

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • I think your second answer is the one OP needs - `?graph.data.frame` and `?graph.constructors` will provide some more info. – thelatemail Jan 29 '14 at 00:43
  • The problem is that I cannot input the data manually and the code does not work for a csv file. It again gives the same error - graph.edgelist expects a matrix with two columns. And graph.data.frame does not give a result either. – user2203793 Jan 29 '14 at 01:01