Reputation: 575
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")
Upvotes: 1
Views: 532
Reputation: 2335
You can use the graph_from_edgelist
function
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')]))
For your properties, you can uses set_edge_attr
as detailed by @P Lapointe below. Extending my code accordingly looks like this:
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
Upvotes: 2
Reputation: 16277
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)
Upvotes: 2