2012-02-16 101 views
4

我在R中使用igraph包来做一些相当简单的事情:计算我网络中两个节点之间的最短距离。是否有直接的方法来提取通过get.shortest.paths()计算的路径的距离?找到距离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) ?? 

回答

6

可以使用shortest.paths功能, 如:

# 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

+0

谢谢!我已更新我的代码以反映该解决方法是不正确的。顺便说一句 - 你是如何绘制网络的(如图所示)? – 2012-02-16 21:58:09

+0

@ baha-kev:实际上,我刚刚使用'tkplot(图)'绘制图形,然后手动添加了顶点名称和边缘权重;) – digEmAll 2012-02-16 22:02:42

+0

非常酷;谢谢 - – 2012-02-17 00:55:49