15

I'm working with igraph for R. My graph is based on an edgelist which includes parallel edges (more than one edge with the same source and target). I would like to convert these parallel edges to an edge attribute weight. Is there an eay way to do this?

If there is no easy way. how can I identify these parallel edges?

    duplicated(E(net))

does not return a single duplicate. I suppose its looking for duplicated edge ids.

Luuklag
  • 3,897
  • 11
  • 38
  • 57
supersambo
  • 811
  • 1
  • 9
  • 25

3 Answers3

29

You can also use E(graph)$weight <- 1 followed by simplify(graph, edge.attr.comb=list(weight="sum")) to assign a weight of 1 to each edge and then collapsing multiple edges into single ones while summing the weights.

Tamás
  • 47,239
  • 12
  • 105
  • 124
  • 4
    This solution is actually much better, because it uses linear space and time, whereas the adjacency matrix solution uses quadratic (in terms of the number of vertices) space and time. – Gabor Csardi Oct 22 '12 at 00:38
  • 2
    Btw. this also eliminates loop edges, so if you don't want that, use the `remove.loops=FALSE` argument to `simplify()`. – Gabor Csardi Oct 22 '12 at 00:39
5

It seems exporting an unweighted graph with parallel edges to an adjacency matrix in igraph creates a weights list with the number of edges as weight, which can then be read again:

library("igraph")
E <- matrix(c(1,1,1,2,2,2),3,2)
G <- graph.edgelist(E)

G2 <- graph.adjacency(get.adjacency(G),weighted=TRUE)
Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
1

In case you want to get the number of parallel edges of a graph without adding a weight attribute to your graph, you could use the following function:

duplicated <- function(graph){
  g_local <- graph
  E(g_local)$weight <- 1
  g_simp <- simplify(g_local, edge.attr.comb=list(weight="sum"))
  w <- E(g_simp)$weight
  return(sum(w-1))
}