Найти расстояние маршрута от get.shortest.paths () - PullRequest
5 голосов
/ 16 февраля 2012

Я использую пакет 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 ) ??

1 Ответ

7 голосов
/ 17 февраля 2012

Вы можете использовать функцию shortest.paths, e.g.:

# 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

...