将边列表合并到单个图中

merge edgelists to a single graph

我有三个具有相同节点的边缘列表。我想将它们合并到一个图中,并通过颜色和权重将这些边分开。我提供了我想做的事的小例子:

df1
a   b   1   blue
b   c   0.361973313 blue
a   d   0.343729742 blue
df2
a   c   0.264800107 green
a   a   0.228507399 green
c   d   0.22202394  green
df3
d   d   0.179089391 red
d   a   0.173410831 red
c   b   0.093636709 red

顶级数据框是我的边缘列表。如您所见,可以自由拥有多个边和环。我想到将这些边合并为单个图的一种方法是制作一个空图,然后分别添加这些边,但我做不到。任何的想法?

g <- make_empty_graph(n = 0, directed = F)
g <- g + vertices(c("a","b", "c","d"))

g<- g+ edges(c( "a", "b", "b", "c",
                "a", "d"),color="blue")

您可以使用graph_from_edgelist函数

library(igraph)

df1 <- data.frame(
  'from' = c('a','b','a'),
  'to' = c('b','c','d'),
  'weight' = c(0.3, 0.2, 0.5),
  'colour' = c('blue','blue','blue'))
  
df2 <- data.frame(
  'from' = c('a','a','c'),
  'to' = c('c','a','d'),
  'weight' = c(0.3, 0.2, 0.5),
  'colour' = c('green','green','green'))

edges <- rbind(df1, df2)

gp <- graph_from_edgelist(
  as.matrix(edges[,c('from', 'to')]))

编辑:

对于您的属性,您可以使用下面@P Lapointe 详述的 set_edge_attr。相应地扩展我的代码如下所示:

gp <- set_edge_attr(gp, "weight", value = edges$weight)
gp <- set_edge_attr(gp, "colour", value = edges$colour)

plot(gp, edge.width = E(g)$weight) #Stolen from P Lapointe

以下是如何使用 graph_from_data_frame 执行此操作。您还必须使用 set_edge_attr 来设置属性。最后,您的体重非常接近,所以很难看出差异。我将一个权重更改为 5 以表明它有效。

df1 <- read.table(text="from to weight color
a   b   1   blue
b   c   0.361973313 blue
a   d   0.343729742 blue",
                 header=TRUE,stringsAsFactors=FALSE)

df2 <- read.table(text="from to weight color
a   c   0.264800107 green
a   a   0.228507399 green
c   d   5  green",
                  header=TRUE,stringsAsFactors=FALSE)


df <- rbind(df1,df2)

g <- graph_from_data_frame(df[,1:2])%>%
  set_edge_attr("weight",value=df$weight) %>%
  set_edge_attr("color",value=df$color)

plot(g, edge.width = E(g)$weight)