[英]How to access the visited vertices in a given shortest path using R igraph
I use all_shortest_paths
function to identify all the shortest paths for given two vertices. 我使用
all_shortest_paths
函数来识别给定两个顶点的所有最短路径。
I do not know the differences, but the following two functions give me the same results 我不知道它们之间的区别,但是以下两个函数给我相同的结果
all_shortest_paths(g, 1,3)
get.all.shortest.paths(g, 1,3)
Here is the outcome 这是结果
$res
$res[[1]]
+ 3/9 vertices, from a86e634:
[1] 1 4 3
$res[[2]]
+ 3/9 vertices, from a86e634:
[1] 1 2 3
$nrgeo
[1] 1 1 2 1 1 0 1 1 1
Now, I want to get the nodes that are visited in a path without the source and sink nodes. 现在,我想获得在没有源节点和宿节点的路径中访问的节点。 For instance, I get the first shortest path.
例如,我得到第一个最短的路径。
> all_shortest_paths(g, 1,3)$res[1]
[[1]]
+ 3/9 vertices, from a86e634:
[1] 1 4 3`
How can I store the nodes that are visited excluding the source and sink nodes (ie, 1,3)? 如何存储除源节点和宿节点(即1,3)之外的已访问节点? When I assign
a<- all_shortest_paths(g, 1,3)$res[1]
, its type seems like list, but no matter what I am doing, I cannot access 4. It keeps returning me + 3/9 vertices, from a86e634: [1] 1 4 3
当我分配
a<- all_shortest_paths(g, 1,3)$res[1]
,它的类型看起来像列表,但是无论我在做什么,我都无法访问4。它会不断+ 3/9 vertices, from a86e634: [1] 1 4 3
返回+ 3/9 vertices, from a86e634: [1] 1 4 3
You need to go one more level down the list returned by all_shortest_paths
. 您需要再下一层
all_shortest_paths
返回的列表。 In the code below I create the variable n
to make it more readable. 在下面的代码中,我创建了变量
n
以使其更具可读性。
library(igraph)
g <- make_graph("Cubical")
p <- all_shortest_paths(g, 1, 3)
n <- length(p[[1]][[1]])
p[[1]][[1]][-c(1, n)]
#+ 1/8 vertex, from 0de75ff:
#[1] 4
To get all inner vertices in one go, use lapply
on p[[1]]
. 要一次性获得所有内部顶点,请对
p[[1]]
使用lapply
。
lapply(p[[1]], function(.p){
n <- length(.p)
.p[-c(1, n)]
})
#[[1]]
#+ 1/8 vertex, from 0de75ff:
#[1] 4
#
#[[2]]
#+ 1/8 vertex, from 0de75ff:
#[1] 2
This code does not depend on the number of inner vertices, as can be seen if the source and sink are 1 and 7. 该代码不取决于内部顶点的数量,可以看出源和宿为1和7。
This time a one-liner. 这次是单线。
(Output omitted.) (省略输出。)
p2 <- all_shortest_paths(g, 1, 7)
lapply(p2[[1]], function(.p) .p[-c(1, length(.p))])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.