从get.shortest.paths()查找与路线距离有关的第二个变量的总数 [英] Find total of second variable related to the distance of route from get.shortest.paths()

查看:127
本文介绍了从get.shortest.paths()查找与路线距离有关的第二个变量的总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了以下问题(查找从get到路线的距离。 shortest.paths())非常有帮助,但希望将其更进一步。我在数据框中添加了一列,我想获得与最小newcost路径有关的总距离。

I found the following question ( Find distance of route from get.shortest.paths() ) very helpful, but would like to take it one step further. I have added one column to the data frame and I would like to get the "total distance" related to the min newcost path.

在我使用的igraph / R代码下面。

Below the igraph / R code that I used.

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。

The question that I would like to have answered is what is the distance related to this shortest path. The answer of the shortest path is 34.5 and (computed manually) the distance related to this path is 208.

了解一些有关如何自动获取此距离的提示。

Appreciate some hints on how to get this distance automatically.

谢谢! Jochem

Thanks! Jochem

# What is the distance related to the min newcost?


推荐答案

这将为您提供最佳路径的边缘:

This gives you the edges along your optimal path:

optimal.path <- V(g2)[tmp2[[1]]] 
E(g2, path = optimal.path)
# Edge sequence:
#               
# [1] 326 -- 234
# [3] 241 -- 326
# [4] 245 -- 241

(请注意,它们不会按照最佳路径的顺序出现,而是它们出现在图形的定义 g2 中。)

(note that they do not appear in the order along your optimal path, but as they appear in the definition of your graph g2.)

,这将为您提供总距离:

and this gives you the total distance:

sum(E(g2, path = optimal.path)$distance)
# [1] 208

这篇关于从get.shortest.paths()查找与路线距离有关的第二个变量的总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆