2014-10-12 133 views
2

我的代碼段是如下:ř的igraph最短距離

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')] 

雖然它返回結果12,我需要得到在這種情況下應該是一個的最短路徑 - B - d - 克 - 電子 - 我 - j。我試圖使用get.shortest.paths(),但徒勞無功。

回答

2

嘗試使用get.all.shortest.paths()。考慮到可能存在多個短路徑(例如,在'a'和'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" 
+0

但是,也許OP只需要一個路徑?無論如何,'get.shortest.paths()',AFAIK沒有錯。 – 2014-10-13 13:09:49

+0

@GaborCsardi根本沒有問題!但我認爲OP對某個特定的路徑感興趣,而AFAIK可能不是'get.shortest.path()'(?)返回的解決方案。因此,我建議'get.all.shortest.paths()'。 – ddiez 2014-10-13 14:02:21

2

你用get.shortest.paths試了一下?由於這種工作原理:

> 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返回長度爲1的名單,因爲我只要求它來計算從「A」到「J」的最短路徑,所以我把它的第一個元素。

+0

拋出錯誤:'[.igraph.vs'(V(gdf) ,get.shortest.paths(gdf,「a」,「j」,權重= E(gdf)$ dist)[[1]]): 無效索引頂點seq – PB4133944 2014-10-12 14:52:23

+0

什麼?哪些代碼會產生該錯誤?我的代碼是否會失敗? 'get.shortest.paths(gdf,「a」,「j」,權重= E(gdf)$ dist)'對我來說工作得很好,所以你必須做其他事情。編輯你的問題。 – Spacedman 2014-10-12 14:57:53