gpt4 book ai didi

r - 从 get.shortest.paths() 查找路线的距离

转载 作者:行者123 更新时间:2023-12-04 11:43:55 27 4
gpt4 key购买 nike

我正在使用 igraph在 R 中打包来做一些相当简单的事情:计算我的网络中两个节点之间的最短距离。是否有一种直接的方法来提取通过 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 ,如下图所示:

enter image description here

关于r - 从 get.shortest.paths() 查找路线的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9317923/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com