查找距离 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 ) ??
I'm using the igraph
package in R to do something rather simple: Calculate the shortest distance between two nodes in my network. Is there a straightforward way to extract the distance of a path calculated via get.shortest.paths()
?
Here is some reproducible code that exemplifies my problem:
## 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 ) ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
shortest.paths
函数,例如:
算法计算出的距离为
34.5 = 11 + 8.2 + 15.3
,如下图:You can use
shortest.paths
function,e.g.:
The distance computed by the algorithm is
34.5 = 11 + 8.2 + 15.3
, as shown in the following picture: