Search code examples
redge-list

Creating edge list in R


I have data like this:

ID=c(rep("ID1",3), rep("ID2",2), "ID3", rep("ID4",2))
item=c("a","b","c","a","c","a","b","a")

data.frame(ID,item)

ID1 a
ID1 b
ID1 c
ID2 a
ID2 c
ID3 a
ID4 b
ID4 a

and I would need it as a list of edges like this:

a;b
b;c
a;c
a;c
b;a

the first three edges coming from ID1, fourth from ID2, ID3 has no edges so nothing from that and fifth from ID4. Any ideas on how to accomplish this? melt/cast?


Solution

  • Try

     res <- do.call(rbind,with(df, tapply(item, ID, 
             FUN=function(x) if(length(x)>=2) t(combn(x,2)))))
      paste(res[,1], res[,2], sep=";")
     #[1] "a;b" "a;c" "b;c" "a;c" "b;a"