R:使用列中的逗号分隔值制作网络图
R: Making a network graph using comma separated values in a column
有什么方法可以制作这样的网络图,例如:
Colour IDs
Red 12,14,15
Green 17,20,25
Blue 20,39,46
其中 (12,14,15)
是网络,(17,20,25)
是网络,(20,39,46)
也是网络,但是 20
来自 Green
和 Blue
将连接。
是否有此功能,或者我是否必须手动拆分逗号分隔值?
谢谢!
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)
您可以试试下面的代码
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()
其中 combn
生成边列表
使用 tidyverse
和 igraph
库:
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()
当某些组只有一个节点时的替代方案:
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()
有什么方法可以制作这样的网络图,例如:
Colour IDs
Red 12,14,15
Green 17,20,25
Blue 20,39,46
其中 (12,14,15)
是网络,(17,20,25)
是网络,(20,39,46)
也是网络,但是 20
来自 Green
和 Blue
将连接。
是否有此功能,或者我是否必须手动拆分逗号分隔值?
谢谢!
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)
您可以试试下面的代码
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()
其中 combn
生成边列表
使用 tidyverse
和 igraph
库:
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()
当某些组只有一个节点时的替代方案:
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()