Creating an adjacency list from data.frame

I have a data.frame with 2 columns: Node A, Node B. Each entry in the frame implies an edge in the graph between Node A and B.

To convert this data.frame to an adjacency list, there must be a good one-liner. Any clues?

+6
r igraph
source share
4 answers

Quick and dirty ...

> edges <- data.frame(nodea=c(1,2,4,2,1), nodeb=c(1,2,3,4,5)) > adjlist <- by(edges, edges$nodea, function(x) x$nodeb) > for (i in as.character(unique(edges$nodea))) { + cat(i, ' -> ', adjlist[[i]], '\n') + } 1 -> 1 5 2 -> 2 4 4 -> 3 > adjlist edges$nodea: 1 [1] 1 5 ------------------------------------------------------------ edges$nodea: 2 [1] 2 4 ------------------------------------------------------------ edges$nodea: 4 [1] 3 
+6
source share

Since you marked this igraph , how about using inline functions?

 > g <- graph.data.frame( edges ) > adjlist <- get.adjedgelist(g) 

Only a caveat is vertices with a zero index that will change with igraph 0.6.

+11
source share
 > edges <- data.frame(nodea=c(1,2,4,2,1), nodeb=c(1,2,3,4,5)) > attach(edges) > tapply(nodeb,nodea,unique) $`1` [1] 1 5 $`2` [1] 2 4 $`4` [1] 3 
+4
source share

how would you present an adjacency list in R? he needs variable-sized lists for a set of neighboring nodes; so you need to use list (); but then what good is it in R?

I can think of lame tricks with similar functions, but they do a linear scan for each node. but playing for 1 minute, here is: a list of paired lists, where the second element of each pair is an adjacency list. the output is more crazy than it really is.

 > edgelist=data.frame(A=c(1,1,2,2,2),B=c(1,2,2,3,4)) > library(plyr) > llply(1:max(edgelist), function(a) list(node=a, adjacents=as.list(edgelist$B[edgelist$A==a]))) [[1]] [[1]]$node [1] 1 [[1]]$adjacents [[1]]$adjacents[[1]] [1] 1 [[1]]$adjacents[[2]] [1] 2 [[2]] [[2]]$node [1] 2 [[2]]$adjacents [[2]]$adjacents[[1]] [1] 2 [[2]]$adjacents[[2]] [1] 3 [[2]]$adjacents[[3]] [1] 4 [[3]] [[3]]$node [1] 3 [[3]]$adjacents list() [[4]] [[4]]$node [1] 4 [[4]]$adjacents list() 
0
source share

All Articles