5

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 ) ??
baha-kev
  • 3,029
  • 9
  • 33
  • 31

1 Answers1

8

You can use shortest.paths function, 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')]

The distance computed by the algorithm is 34.5 = 11 + 8.2 + 15.3, as shown in the following picture:

enter image description here

digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • Thanks!I have updated my code to reflect how the workaround was incorrect. BTW - how did you plot the network (as shown)? – baha-kev Feb 16 '12 at 21:58
  • 1
    @baha-kev: Actually, I have just plotted the graph using `tkplot(graph)` then I added vertices names and edges weights by hand ;) – digEmAll Feb 16 '12 at 22:02
  • Is there a way to programmatically arrive at the exact nodes(path taken) which were actually traversed to yield the result i.,e., 34.5 ? – ZeroGraviti Apr 19 '17 at 02:51
  • @ZeroGraviti: the original poster was using `get.shortest.paths(g2, from='234', to='245',weights=E(g2)$newcost)` which does exactly that... – digEmAll Apr 19 '17 at 07:43
  • @digEmAll I meant the path i.e., 0 -> 2 -> 3 ->4 – ZeroGraviti Apr 20 '17 at 03:16
  • @ZeroGraviti: have you tried to run the code in the question? `V(g2)[tmp2[[1]]]` returns the sequence of nodes in the shortest path, i.e. `234->326->241->245`. – digEmAll Apr 20 '17 at 06:09
  • 3
    @ZeroGraviti: sorry, actually with the new version it should be : `tmp2$vpath[[1]]` – digEmAll Apr 20 '17 at 07:34