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!
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()
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()