简体   繁体   中英

R igraph shortest distance

My code snippet is as below:

df = as.data.frame(rbind(
  c("a","b",2),
  c("b","d",2),
  c("d","g",2),
  c("g","j",8),
  c("j","i",2),
  c("i","f",6),
  c("f","c",2),
  c("c","a",4),
  c("c","e",4),
  c("e","h",2),
  c("h","j",4),
  c("e","g",1),
  c("e","i",3),
  c("e","b",7)
  ))
names(df) = c("start_node","end_node","dist")

# Convert this to "igraph" class
gdf <- graph.data.frame(df, directed=FALSE)

# Compute the min distances from 'a' to all other vertices
dst_a <- shortest.paths(gdf,v='a',weights=E(gdf)$dist)

# Compute the min distances from 'a' to 'j'
dst_a[1, which(V(gdf)$name == 'j')]

While it returns the result 12, I need to get the shortest path which in this case should be a - b - d - g - e - i - j. I have tried to use get.shortest.paths(), but in vain.

What did you try with get.shortest.paths ? Because this works:

> V(gdf)[get.shortest.paths(gdf,"a","j",weights=E(gdf)$dist)[[1]]]
Vertex sequence:
[1] "a" "b" "d" "g" "e" "i" "j"

get.shortest.paths returns a list of length 1 because I'm only asking it to calculate the shortest path from "a" to "j", so I take the first element of it.

Try using get.all.shortest.paths() . Take into account that there may be more than one short path (eg try the same between 'a' and 'e')

sp=get.all.shortest.paths(gdf, "a", "j",weights=E(gdf)$dist)
sp
$res
$res[[1]]
[1] 1 2 3 4 9 6 5


$nrgeo
 [1] 1 1 1 1 1 1 1 1 1 1

V(gdf)[sp$res[[1]]]$name
[1] "a" "b" "d" "g" "e" "i" "j"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM