我是图表的新手,并期望这是非常基本的东西。
我有一个有向图(水文网络),我想从最短路径的边缘抓取一个属性。例如:
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)
返回:
[1] "A" "B"
如果我想获得到达网络末端的最短路径的标签:
idx <- shortest_paths(g, 1, 4, output = "epath")$epath[[1]]
igraph::edge_attr(g, "id", idx)
我明白了:
Warning message:
In shortest_paths(g1, 1, 4, output = "epath") :
At structural_properties.c:740 :Couldn't reach some vertices
idx
是:
+ 0/4 edges from b8aaa81 (vertex names):
对于最后一个我希望得到[1] "A" "B" "C"
如何获取包含图形最终顶点的最短路径的标签?
答案 0 :(得分:1)
问题在于你引用顶点的方式。请注意,顶点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"
`