r - 求节点 u 和 v 之间经过节点 g 的最短路径总数

标签 r igraph network-analysis

我有以下矩阵,可以生成无向网络图:

  a b c d e f g h i j
a 0 1 1 0 0 0 0 0 0 0
b 1 0 1 0 0 0 0 0 0 0
c 1 1 0 1 1 0 1 0 0 0
d 0 0 1 0 1 0 0 0 0 0
e 0 0 1 1 0 1 0 0 0 0
f 0 0 0 0 1 0 1 0 0 0
g 0 0 1 0 0 1 0 1 0 0
h 0 0 0 0 0 0 1 0 1 1
i 0 0 0 0 0 0 0 1 0 0
j 0 0 0 0 0 0 0 1 0 0

m <- structure(c(0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 0L, 0L, 
0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 
1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 
0L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 
0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 1L, 0L, 0L), .Dim = c(10L, 10L), .Dimnames = list(
    c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"), c("a", 
    "b", "c", "d", "e", "f", "g", "h", "i", "j")))

library(igraph)
g3n <- graph.adjacency(m)

我有兴趣手动计算节点“g”的介数,这需要在所有可能的节点中找到最短路径作为分母和分子,因为最短路径的数量包含节点“g”。

我使用以下代码生成所有节点之间最短路径的长度:

shortest.paths(g3n, v=V(g3n), to=V(g3n))

最短路径矩阵:

  a b c d e f g h i j
a 0 1 1 2 2 3 2 3 4 4
b 1 0 1 2 2 3 2 3 4 4
c 1 1 0 1 1 2 1 2 3 3
d 2 2 1 0 1 2 2 3 4 4
e 2 2 1 1 0 1 2 3 4 4
f 3 3 2 2 1 0 1 2 3 3
g 2 2 1 2 2 1 0 1 2 2
h 3 3 2 3 3 2 1 0 1 1
i 4 4 3 4 4 3 2 1 0 2
j 4 4 3 4 4 3 2 1 2 0

有没有一种方法可以计算两个节点之间的最短路径包含节点“g”作为矩阵的次数,或者只是在 R 中以任何其他方式?

最佳答案

所以,我不确定这个解决方案有多优雅,但以下应该可行:

#initialize a list to populate with all the shortest paths in the graphy
allpaths <- list()


#Assuming this is an undirected graph, we don't want to calculate both a %--% b and b %--% a  
for(x in V(g3n)$name){
  for(y in V(g3n)$name){
    if(x < y){
      shortest_path_options <- all_shortest_paths(g3n, x, y)$res

      #sometimes there are multiple shortest paths, we will include them all
      for(z in shortest_path_options){
        allpaths[[length(allpaths)+1]] <- z$name
      }
    }
}

#create a boolean of whether a shortest path contains 'g' or not
allpaths_bool <- sapply(allpaths, function(x){
  ('g' %in% x) & (head(x, 1) != 'g') & (tail(x, 1) != 'g')
  })

#Show all the paths that contain 'g'
allpaths[allpaths_bool]

您可以通过将所有内容包装到 sapply 函数中来计算每个顶点的值。

sapply(V(g3n)$name, function(x){
  temp_bool <- sapply(allpaths, function(y){
    (x %in% y) & (head(y, 1) != x) & (tail(y, 1) != x)
  })
  length(allpaths[temp_bool])
})

}

必须有一种更简单的方法,但我不太确定。可能有一种方法可以通过使用提供中间中心性测量的 Betweeness 函数来推断此信息,但我对图论的了解不是很深入。

关于r - 求节点 u 和 v 之间经过节点 g 的最短路径总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52506533/

相关文章:

r - glmnet 未从 cv.glmnet 收敛 lambda.min

r - 尝试在 R 中传播数据框

python - 在 Mac OSX Sierra 中安装 python-igraph

r - 将数据框转换为邻接矩阵/边列表以进行网络分析

julia - SimpleHypergraphs.jl - 从文本文件加载超图

r - 如何为smooth.spline()选择平滑参数?

R - 从列中的值中删除逗号并将分隔的值放入新行中

r - 什么是社区检测中的成员资格?

r - 使用现有 R 应用程序/包可视化协作网络结构

r - 如何将数据转换为边列表