2014-10-12 119 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