[英]Find total of second variable related to the distance of route from get.shortest.paths()
[英]Find distance of route from get.shortest.paths()
我在R中使用igraph
包來做一些相當簡單的事情:計算網絡中兩個節點之間的最短距離。 有沒有一種直接的方法來提取通過get.shortest.paths()
計算的路徑的距離?
以下是一些可重現的代碼,可以解釋我的問題:
## reproducible code:
df2 = rbind(c(234,235,21.6),
c(234,326,11.0),
c(235,241,14.5),
c(326,241,8.2),
c(241,245,15.3),
c(234,245,38.46))
df2 = as.data.frame(df2)
names(df2) = c("start_id","end_id","newcost")
require(igraph)
g2 <- graph.data.frame(df2, directed=FALSE)
class(g2)
print(g2, e=TRUE, v=TRUE)
## calculate shortest path between vertex 234 and 245
(tmp2 = get.shortest.paths(g2, from='234', to='245',weights=E(g2)$newcost))
## print route vertices:
V(g2)[tmp2[[1]]]
## print distance of each route segment:
## ??
## calculate distance using 'newcost' weights:
## ?? sum( route segments ) ??
您可以使用shortest.paths
函數,例如:
# compute the min distances from '234' to all other vertices
tmp3 <- shortest.paths(g2,v='234',weights=E(g2)$newcost)
# print min distance from '234' to '245'
tmp3[1, which(V(g2)$name == '245')]
算法計算的距離為34.5 = 11 + 8.2 + 15.3
,如下圖所示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.