Search code examples
rnetworkinggraphigraphedge-list

merge edgelists to a single graph


I have three edgelists that have same nodes. I want to merge them into one graph and seperate these edges by colors and weights. I have provide small example of what I want to do:

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

top dataframes are my edgelists. As you can see multiple edges and loops are free to have. A way that came to my mind to merge these edges to a single graph was to make a empty graph and then add these edges seperately, but I couldn't do it. Any idea?

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")

Solution

  • Here's how to do that using graph_from_data_frame. You also have to use set_edge_attr to set the attributes. Finally, your weights are very close to another, so the difference is hard to see. I changed one weight to 5 to show that it works.

    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)
    

    enter image description here