[英]Find total of second variable related to the distance of route from get.shortest.paths()
我發現以下問題( 找到距get.shortest.paths()的路線的距離 )非常有幫助,但希望將其更進一步。 我在數據框中添加了一列,我想獲得與最小newcost路徑有關的“總距離”。
在我使用的igraph / R代碼下面。
df2 = rbind(c(234,235,21.6,75),
c(234,326,11.0,35),
c(235,241,14.5,78),
c(326,241,8.2,98),
c(241,245,15.3,75),
c(234,245,38.46,65))
df2 = as.data.frame(df2)
names(df2) = c("start_id","end_id","newcost","distance")
df2
require(igraph)
g2 <- graph.data.frame(df2, directed=FALSE)
tkplot(g2)
(tmp2 = get.shortest.paths(g2, from='234', to='245',weights=E(g2)$newcost))
# This gives the shortest path based on $newcost
V(g2)[tmp2[[1]]]
我想回答的問題是與這條最短路徑有關的距離是多少。 最短路徑的答案是34.5,並且(手動計算)與該路徑有關的距離是208。
贊賞一些有關如何自動獲得此距離的提示。
謝謝! 約赫姆
# What is the distance related to the min newcost?
這為您提供了最佳路徑的邊緣:
optimal.path <- V(g2)[tmp2[[1]]]
E(g2, path = optimal.path)
# Edge sequence:
#
# [1] 326 -- 234
# [3] 241 -- 326
# [4] 245 -- 241
(請注意,它們並不是沿着您的最佳路徑的順序出現,而是出現在圖形g2
的定義中)。
這將為您提供總距離:
sum(E(g2, path = optimal.path)$distance)
# [1] 208
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.