[英]Find total of second variable related to the distance of route from get.shortest.paths()
[英]Distance Matrix from second variable using get.shortest.paths()
我想進一步解決這個問題( 從get.shortest.paths()查找與路徑距離有關的第二個變量的總和 )。 當使用newcost變量找到“最短”路徑時,如何獲得節點之間的距離矩陣?
(我對igraph的經驗非常有限)。
df2 = rbind(c(234,235,21.6,75),
c(234,326,11.0,35),
c(235,241,14.5,78),
c(326,241,8.2,98),
c(241,245,15.3,75),
c(234,245,38.46,65))
df2 = as.data.frame(df2)
names(df2) = c("start_id","end_id","newcost","distance")
require(igraph)
g2 <- graph.data.frame(df2, directed=FALSE)
tmp2 = shortest.paths(g2,weights=E(g2)$newcost)
tmp2 #this gives the matrix of newcost-weighted shortest distances
我可以使用幫助的地方是如何找到所有路徑,例如,使用optimal.path <- get.shortest.paths
,並使用sum(E(g2, path = optimal.path)$distance)
創建距離矩陣
我真正想要的是所有節點對的距離邊緣列表,例如:
startid endid shortestdist
234 235 75
234 245 208
關於此問題的棘手問題是,使用newcost來查找最短路徑,但是我想要的是另一個變量的總和-節點對之間每個最短路徑上的距離變量。
好的,首先讓我明確說明我自己不是igraph
用戶。 不過,我認為這個問題很有趣,所以我想看看。 而且我也找不到解決您所遇到問題的簡便方法。 最后,我做了一些輔助功能以使該過程成為可能。 我很有可能已經在igraph
重新編碼了功能,但找不到。
讓我首先定義get.shortest.paths.for.all
,它不僅會返回給定屬性的最短路徑長度,還將自己返回圖中所有頂點的最短路徑。 這是代碼
get.shortest.paths.for.all<-function(graph, attr) {
paths<-lapply(1:(vcount(graph)-1), function(i) {
get.all.shortest.paths(
graph,
weights=get.edge.attribute(g2,attr),
from = V(graph)[i],
to = V(graph)[(i+1):vcount(graph)]
)$res
})
unsplit(paths, rep.int(seq_along(paths), sapply(paths, length)))
}
現在讓我定義get.path.dist.matrix
將獲取一個圖形和一個路徑列表(例如get.shortest.paths.for.all
返回的get.shortest.paths.for.all
),並計算每個路徑之間給定屬性的距離
get.path.dist.matrix<-function(graph, path, attr) {
dd<-get.adjacency(graph, attr=attr)
uniqs <- numeric(0)
if (is.list(path)) {
starts<-sapply(path, head, 1)
ends<-sapply(path, tail, 1)
uniqs <- unique(sort(c(starts,ends)))
} else {
uniqs <- c(head(path,1), tail(path,1))
}
m<-matrix(0, nrow=length(uniqs), ncol=length(uniqs),
dimnames=list(V(graph)$name[uniqs],V(graph)$name[uniqs]))
for(pp in path) {
m[pp[1], pp[length(pp)]]<-sum(dd[embed(pp,2)])
}
m+t(m)
}
使用您的樣本數據,我像這樣使用它們
paths <- get.shortest.paths.for.all(g2, "newcost")
get.path.dist.matrix(g2, paths,"distance")
# 234 235 326 241 245
# 234 0 75 35 133 208
# 235 75 0 176 78 153
# 326 35 176 0 98 173
# 241 133 78 98 0 75
# 245 208 153 173 75 0
這似乎是合理的,並且與shortest.paths(g2,weights=E(g2)$distance)
。 為了測試我的功能,我看到
all(tmp2==get.path.dist.matrix(g2, paths,"newcost"))
因此,請隨時嘗試這些,如果您發現任何問題或可能的改進,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.