Milo - 1 year ago 110

R Question

My problem is very simple: I need to create an adjacency list/matrix from a list of edges.

I have an edge list stored in a csv document with column1 = node1 and column2 = node2 and I would like to convert this to a weighted adjacency list or a weighted adjacency matrix.

To be more precise, here's how the data looks like -where the numbers are simply node ids:

`node1,node2`

551,548

510,512

548,553

505,504

510,512

552,543

512,510

512,510

551,548

548,543

543,547

543,548

548,543

548,542

Any tips on how to achieve the conversion from this to a weighted adjacency list/matrix?

This is how I resolved to do it previously, without success (courtesy of Dai Shizuka):

`dat=read.csv(file.choose(),header=TRUE) # choose an edgelist in .csv file format`

el=as.matrix(dat) # coerces the data into a two-column matrix format that igraph likes

el[,1]=as.character(el[,1])

el[,2]=as.character(el[,2])

g=graph.edgelist(el,directed=FALSE) # turns the edgelist into a 'graph object'

Thank you!

Answer Source

This response uses base R only. The result is a standard matrix used to represent the adjacency matrix.

```
el <- cbind(a=1:5, b=5:1) #edgelist (a=origin, b=destination)
mat <- matrix(0, 5, 5)
mat[el] <- 1
mat
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 0 0 0 1
#[2,] 0 0 0 1 0
#[3,] 0 0 1 0 0
#[4,] 0 1 0 0 0
#[5,] 1 0 0 0 0
```

Here `mat`

is your adjacency matrix defined from edgelist `el`

, which is a simple `cbind`

of the vectors `1:5`

and `5:1`

.

If your edgelist includes weights, then you need a slightly different solution.

```
el <- cbind(a=1:5, b=5:1, c=c(3,1,2,1,1)) # edgelist (a=origin, b=destination, c=weight)
mat<-matrix(0, 5, 5)
for(i in 1:NROW(el)) mat[ el[i,1], el[i,2] ] <- el[i,3] # SEE UPDATE
mat
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 0 0 0 3
#[2,] 0 0 0 1 0
#[3,] 0 0 2 0 0
#[4,] 0 1 0 0 0
#[5,] 1 0 0 0 0
```

**UPDATE**

Some time later I realized that the for loop (3rd line) in the previous weighted edgelist example is unnecessary. You can replace it with the following vectorized operation:

```
mat[el[,1:2]] <- el[,3]
```