如何在R语言中使用igraph提取所有最短路径的边类型
如何用igraph的all_shortest_paths提取所有最短路径的边类型
igraph有两个实用函数,shortest_paths和all_shortest_paths。前者返回单条最短路径,后者返回所有符合条件的最短路径。但前者支持输出路径对应的边类型,后者似乎不具备该能力。
我该如何使用all_shortest_paths提取所有最短路径的「边类型」?以下是问题复现代码:
library(igraph) m <- read.table(row.names=1, header=TRUE, text= " A B C D A 0 1 1 0 B 0 0 0 1 C 0 0 0 1 D 0 0 0 0") m <- as.matrix(m) ig <- graph.adjacency(m, mode="directed") plot(ig) E(ig) for (i in 1:length(E(ig))) { if (i == 4) { E(ig)[i]$type <- -1 } else { E(ig)[i]$type <- 1 } } ### 获取单条最短路径 test1 <- shortest_paths(ig, from = V(ig)[1], to = V(ig)[4], mode = "out", output = "epath") ### 输出单条最短路径对应的边类型 test1$epath[[1]]$type ### 获取所有最短路径 test2 <- all_shortest_paths(ig, from = V(ig)[1], to = V(ig)[4], mode = "out") ### 以下代码无法运行,该如何获取所有最短路径的边类型? test2$res[[1]]$type
解决方案
all_shortest_paths 返回的res字段存储的是顶点序列,而非边序列,因此无法直接提取边的type属性。你可以将顶点序列两两配对,查询对应的边ID后再调取属性即可,实现代码如下:
# 遍历所有最短路径,批量提取边类型 all_path_types <- lapply(test2$res, function(vtx_path) { # 按相邻顶点配对查询对应边ID edge_ids <- get.edge.ids(ig, vp = as.numeric(vtx_path)) # 返回边的type属性 E(ig)[edge_ids]$type }) # 输出所有路径的边类型 print(all_path_types)
运行上述代码后,将得到示例中两条最短路径对应的边类型:
- 第一条路径A->B->D的边类型为
1 1 - 第二条路径A->C->D的边类型为
1 -1
如果你需要获取和shortest_paths输出格式一致的边序列,只需将返回值替换为E(ig)[edge_ids]即可。
内容的提问来源于stack exchange,提问作者Nova
相关产品推荐
相关产品推荐

