williamhrs
williamhrs

Reputation: 35

R: convert table to adjacency matrix or edgelist

I have the following table

1   "x1"    "x2"            
1   "x1"    "x2"    "x3"
1   "x1"    "x2"
2   "y1"    "y2"    "y3"
2   "y1"    "y2"    "y3"
3   "y1"    "x2"
3   "z1"    "x2"

I need to transform this table as an adjacency matrix or an edgelist where I can have the first column as an attribute of the edge, and the rest of the columns would be my edges, for example, I would need the lines that have more than 3 edges that they all get connected like this (for line 2):

"x1" "x2" 1
"x1" "x3" 1
"x2" "x3" 1

The one meaning the type of edge that I want.

Is there a way to do this in R or python?

I'm going to plot this with igraph in R.

Upvotes: 2

Views: 940

Answers (1)

MrFlick
MrFlick

Reputation: 206253

I could not find a simple transformation. But using your sample data:

dd <- structure(list(V1 = c(1L, 1L, 1L, 2L, 2L, 3L, 3L), V2 = structure(c(1L, 
1L, 1L, 2L, 2L, 2L, 3L), .Label = c("x1", "y1", "z1"), class = "factor"), 
    V3 = structure(c(1L, 1L, 1L, 2L, 2L, 1L, 1L), .Label = c("x2", 
    "y2"), class = "factor"), V4 = structure(c(1L, 2L, 1L, 3L, 
    3L, 1L, 1L), .Label = c("", "x3", "y3"), class = "factor")), .Names = c("V1", 
"V2", "V3", "V4"), class = "data.frame", row.names = c(NA, -7L))

I ended up creating a few helper functions and using the magrittr syntax that dplyr likes to use to arrive at this

library(magrittr)

smoosh <- function(...) do.call(Map, c(list(cbind.data.frame), list(...)))
collpase <- function(x) do.call(rbind, x)
has.char <- function(x) x[nchar(x)>0]

xx <- dd[-1] %>% as.matrix %>% split( 1:nrow(dd)) %>% lapply(has.char) %>% 
    lapply(combn,2) %>% lapply(t) %>% smoosh(attr=dd$V1) %>% collpase

As you can see there were a bunch of small transformations which is why I chose to use the %>% operator for magrittr rather than nesting them all for readability. But in the end it returns

     1  2 attr
1   x1 x2    1
2.1 x1 x2    1
2.2 x1 x3    1
2.3 x2 x3    1
3   x1 x2    1
4.1 y1 y2    2
4.2 y1 y3    2
4.3 y2 y3    2
5.1 y1 y2    2
5.2 y1 y3    2
5.3 y2 y3    2
6   y1 x2    3
7   z1 x2    3

Upvotes: 2

Related Questions