Counting how many vertices in a neighbourhood have a given attribute with edge weights in igraph for R

你说的曾经没有我的故事 提交于 2019-12-12 19:17:24

问题


This is related to this question. I have a very large graph, on the order of 100,000 vertices in igraph. Each vertex has an attribute att which is a logical value. Edges are weighted with positive integer weights. For each vertex v, I would like to sum the edge weights of edges that connect v to a vertex where att=T.

We can use the following as an example

set.seed(42)
g <- erdos.renyi.game(169081, 178058, type="gnm")
V(g)$att <- as.logical(rbinom(vcount(g), 1, 0.5))

回答1:


Here's one way to get, for each vertex v, the sum of edge weights of neighboring vertices with att=T. Gabor might have a more elegant way that is much faster.

library(igraph)
set.seed(42)
g <- erdos.renyi.game(169081, 178058, type="gnm")
V(g)$att <- as.logical(rbinom(vcount(g), 1, 0.5))
E(g)$weight <- sample(10, ecount(g), replace=TRUE) #integer weights

sumEdgeWeightsOfEdgesFromVertexV<- function(v){
  totwt <- 0
  #get all neighbors of vertex v
  all_neighbors_of_v <- V(g)[nei(v)]
  #subset to those with att to be TRUE
  att_nei <- as.vector(all_neighbors_of_v[all_neighbors_of_v$att==TRUE])
  #sum all the weights, edge by edge
  for( ver in att_nei) {
    totwt <- totwt + E(g, c(v,ver))$weight
  }
  totwt
}  

# sapply(V(g), sumEdgeWeightsOfEdgesFromVertexV)


来源:https://stackoverflow.com/questions/23165452/counting-how-many-vertices-in-a-neighbourhood-have-a-given-attribute-with-edge-w

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