R igraph convert parallel edges to weight attribute

≯℡__Kan透↙ 提交于 2019-11-30 17:57:38

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.

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)

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))
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!