Home > OS >  R: Making a network graph using comma separated values in a column
R: Making a network graph using comma separated values in a column

Time:04-14

Is there a way I can make a network graph like this, for instance:

Colour               IDs
Red                  12,14,15
Green                17,20,25
Blue                 20,39,46

where (12,14,15) will be a network, (17,20,25) will be a network, and (20,39,46) will also be a network, but the 20 from Green and Blue will be connected.

Is there a function for this, or do I have to manually split the comma separated values?

Thank you!

CodePudding user response:

You can try the following code

library(data.table)
library(igraph)

setDT(df)[
    ,
    as.data.frame(t(combn(strsplit(IDs, ",")[[1]], 2))),
    Colour
][
    ,
    .(V1, V2, color = Colour)
] %>%
    graph_from_data_frame(directed = FALSE) %>%
    plot()

where combn generates edge lists

enter image description here

CodePudding user response:

library(data.table)
library(igraph)

DT <- fread("Colour               IDs
Red                  12,14,15
Green                17,20,25
Blue                 20,39,46")


L <- lapply(strsplit(DT$IDs, ","), combn, 2, simplify = FALSE)
names(L) <- DT$Colour
edges <- rbindlist(lapply(L, transpose), idcol = "color")

g <- graph_from_data_frame(edges[, 2:3], directed = FALSE)
E(g)$color <- tolower(edges$color)
plot(g)

enter image description here

CodePudding user response:

Using tidyverse and igraph libraries:

library(tidyverse)
library(igraph)

dat %>% 
  separate_rows(IDs) %>% 
  group_by(Colour) %>% 
  do(data.frame(t(combn(.$IDs, 2)))) %>% 
  select(X1, X2, color = Colour) %>% 
  graph_from_data_frame(directed = F) %>% 
  plot()

enter image description here


An alternative when some groups have only one node:

dat %>% 
  separate_rows(IDs) %>% 
  group_by(Colour) %>% 
  summarise(new = ifelse(n() > 1, paste(combn(IDs, 2), collapse = "-"), as.character(IDs))) %>% 
  separate_rows(new, sep = "(?:[^-]*(?:-[^-]*){1})\\K-") %>% 
  separate(new, into = c("X1", "X2")) %>% 
  select(X1, X2, color = Colour) %>% 
  graph_from_data_frame(directed = F) %>% 
  plot()
  • Related