如何 select 基于图形的长度的某些路径,在 R 中使用 igraph

How to select certain paths of a graph based on their length, using igraph in R

给定一张图,例如:

require(igraph)
g <- graph.famous("Zachary")

这样它的一些属性是:

diameter(g)
[1] 5
> farthest.nodes(g)
[1] 15 17  5
> average.path.length(g)
[1] 2.4082
> path.length.hist(g)
$res
[1]  78 265 137  73   8
$unconnected
[1] 0

如您所见,长度为 5 的路径有 8 条,长度为 4 的路径有 73 条,依此类推...

我希望能够隔离特定长度路径中涉及的节点组。例如,我想知道长度为4的73条路径中涉及的节点,以及它们分别连接的节点。

让我用一个简单的例子来说明这一点,图表的直径。对于这种特殊情况,可以这样做:

##names of the nodes involved in the diameter path of the graph
nodes.diameter<-get.diameter(g) 
edges <- as.data.frame(get.edgelist(g))
edges.diameter <- edges[which(edges$V1 %in% nodes.diameter),]
g.diameter <- graph.data.frame(edges.diameter, directed = FALSE)
##some aesthetics for the plot
V(g.diameter)$label.cex <- 1
plot(g.diameter,vertex.size=10) 

这是一个特殊的例子,因为很容易得到直径的节点名称。但是,有没有办法在给定特定路径长度的情况下获取节点名称?(天真地,类似于 get.path(g,length = X),在天真、理想的世界中,这将 return 包含 length = X 路径中涉及的节点的列表。例如,对于 length = 4,该列表将具有长度为 73 的元素,每个元素包含长度为 4 的 73 条路径中的每条路径所涉及的节点)

非常感谢您抽出宝贵时间。

path.length.hist 函数查看所有可能的最短路径。所以这两个命令是一样的

# path.length.hist(g)$res
[1]  78 265 137  73   8

sp <- shortest.paths(g)
table(sp[upper.tri(sp)])
#   1   2   3   4   5 
#  78 265 137  73   8

这意味着可以从 shortest.paths() 中提取您想要的信息。这是一个函数,它将 return 路径中涉及的顶点的索引

get_paths_by_length <- function(g, len) {
    sp <- shortest.paths(g)
    sp[lower.tri(sp,TRUE)] <- NA
    wp <- which(sp==len, arr.ind=TRUE)
    mapply(function(a,b) get.shortest.paths(g, a, b)$vpath, wp[,1], wp[,2])
}

哪个return

get_paths_by_length(g,5)
# [[1]]
# [1] 15 33  3  1  6 17
# [[2]]
# [1] 16 33  3  1  6 17
# [[3]]
# [1] 17  6  1  3 33 19
# [[4]]
# [1] 17  6  1  3 33 21
# [[5]]
# [1] 17  6  1  3 33 23
# [[6]]
# [1] 17  6  1  3 28 24
# [[7]]
# [1] 17  6  1  9 34 27
# [[8]]
# [1] 17  6  1  3 33 30

对于长度为 5 的八个路径