【问题标题】:Find distance of route from get.shortest.paths()从 get.shortest.paths() 查找路线的距离
【发布时间】:2012-03-08 05:50:15
【问题描述】:

我正在使用 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 ) ??

【问题讨论】:

    标签: r routing dijkstra igraph


    【解决方案1】:

    你可以使用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,如下图:

    【讨论】:

    • 谢谢!我已经更新了我的代码以反映解决方法的不正确之处。顺便说一句 - 你是如何绘制网络的(如图所示)?
    • @baha-kev:实际上,我刚刚使用tkplot(graph) 绘制了图形,然后我手动添加了顶点名称和边权重;)
    • 有没有办法以编程方式到达实际遍历以产生结果的确切节点(采用的路径),即 34.5 ?
    • @ZeroGraviti:原始海报使用的是get.shortest.paths(g2, from='234', to='245',weights=E(g2)$newcost),正是这样做的......
    • @ZeroGraviti:对不起,实际上新版本应该是:tmp2$vpath[[1]]
    猜你喜欢
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    相关资源
    最近更新 更多