R 如何从有向图最短路径提取边属性:

R 如何从有向图最短路径提取边属性:,r,igraph,R,Igraph,我不熟悉图形,希望这是一个相当基本的东西 我有一个有向图(水文网络),我想从最短路径的边上获取一个属性。例如: library(igraph) gdf <- data.frame(from = c(1,2,3,5), to = c(2,3,4,3), id = c("A","B","C","D")) g <- graph_from_data_frame(gdf, directed = TRUE) idx <- shortest_paths(g, 1, 3, output = "

我不熟悉图形,希望这是一个相当基本的东西

我有一个有向图(水文网络),我想从最短路径的边上获取一个属性。例如:

library(igraph)
gdf <- data.frame(from = c(1,2,3,5), to = c(2,3,4,3), id = c("A","B","C","D"))
g <- graph_from_data_frame(gdf, directed = TRUE)
idx <- shortest_paths(g, 1, 3, output = "epath")$epath[[1]]
igraph::edge_attr(g, "id", idx)
如果要获取到网络末端的最短路径的标签:

idx <- shortest_paths(g, 1, 4, output = "epath")$epath[[1]]
igraph::edge_attr(g, "id", idx)
idx
是:

+ 0/4 edges from b8aaa81 (vertex names):
对于最后一个,我希望得到
[1]“A”“B”“C”


如何获取包含图的最终顶点的最短路径的标签?

问题在于引用顶点的方式。请注意,顶点ID与顶点标签不对齐

vertex_attr(g)
$name
[1] "1" "2" "3" "5" "4"
当您编写
最短路径(g,1,4,output=“epath”)$epath[[1]]

它将采用标签为“1”和“5”的第一个和第四个节点。这是失败的,因为没有从“1”到“5”的路径。我相信你的意思是

idx <- shortest_paths(g, "1", "4", output = "epath")$epath[[1]]
igraph::edge_attr(g, "id", idx)
[1] "A" "B" "C"
idx
vertex_attr(g)
$name
[1] "1" "2" "3" "5" "4"
idx <- shortest_paths(g, "1", "4", output = "epath")$epath[[1]]
igraph::edge_attr(g, "id", idx)
[1] "A" "B" "C"