【问题标题】:igraph: summarize each node's neighbours characteristicsigraph:总结每个节点的邻居特征
【发布时间】:2020-12-07 16:47:06
【问题描述】:

使用 igraph 对象我想捕获每个节点的邻居的一些特征,例如其邻居的平均度数。

我想出了这段代码,它不优雅而且很慢。 对于大型复杂的网络,我应该如何重新考虑它?

library(igraph)

# Toy example
set.seed(123)
g <- erdos.renyi.game(10,0.2)

# Loop to calculate average degree of each node's neighbourhood
s <- character(0)
for(i in 1:gorder(g)){
  n <- ego_size(g, nodes = i, order = 1, mindist = 1)
  node_of_interest <- unique(unlist(ego(g, nodes = i, order = 1, mindist = 1)))
  m <- mean(degree(g, v = node_of_interest, loops = TRUE, normalized = FALSE)-1)
  
  s <- rbind(s,data.frame(node = i, neighbours = n, mean = m))

}

【问题讨论】:

    标签: r for-loop igraph neighbours


    【解决方案1】:

    在循环中使用rbind 扩展数据结构在R 中会变得非常慢,因为在每一步它都需要为新对象分配空间,然后复制它(参见第24.6 节here)。此外,如果一个节点是多个节点的邻居,您可能会多次计算该节点的度数。

    一个可能更好的选择可能是:

    # add vertex id (not really necessary)
    V(g)$name <- V(g) 
    
    # add degree to the graph
    V(g)$degree <- degree(g, loops = TRUE, normalized = FALSE)
    
    # get a list of neighbours, for each node
    g_ngh <- neighborhood(g, mindist = 1) 
    
    # write a function that gets the means                       
    get.mean <- function(x){
      mean(V(g)$degree[x]-1)
    }
    
    # apply the function, add result to the graph
    V(g)$av_degr_nei <- sapply(g_ngh, get.mean)
    
    
    # get data into dataframe, if necessary
    d_vert_attr <- as_data_frame(g, what = "vertices")
    
    d_vert_attr
       name degree av_degr_nei
    1     1      0         NaN
    2     2      1   2.0000000
    3     3      2   1.0000000
    4     4      1   1.0000000
    5     5      2   1.0000000
    6     6      1   1.0000000
    7     7      3   0.6666667
    8     8      1   0.0000000
    9     9      1   0.0000000
    10   10      0         NaN
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 2016-03-30
      相关资源
      最近更新 更多