user2203793
user2203793

Reputation: 135

Adjacency matrix in R

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?

Upvotes: 10

Views: 40772

Answers (2)

Brian Diggs
Brian Diggs

Reputation: 58845

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

Upvotes: 22

Tyler Rinker
Tyler Rinker

Reputation: 110004

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

Upvotes: 10

Related Questions