r - How to extract edge attributes from a directed graph shortest path:
问题描述
I am new to graphs and expect this is something fairly basic.
I have a directed graph (a hydrology network) and I want to grab an attribute from the edges in a shortest path. For example:
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)
Which returns:
[1] "A" "B"
If I want to get the labels for the shortest path to the end of the network:
idx <- shortest_paths(g, 1, 4, output = "epath")$epath[[1]]
igraph::edge_attr(g, "id", idx)
I get:
Warning message:
In shortest_paths(g1, 1, 4, output = "epath") :
At structural_properties.c:740 :Couldn't reach some vertices
And idx
is:
+ 0/4 edges from b8aaa81 (vertex names):
For this last one I would have expected to get [1] "A" "B" "C"
How do I get the labels for a shortest path that includes the final vertex of the graph?
解决方案
问题是您引用顶点的方式。请注意,顶点 ID 不与顶点标签对齐。
vertex_attr(g)
$name
[1] "1" "2" "3" "5" "4"
当你写shortest_paths(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"
`