[英]Find All Shortest Paths using igraph/R
首先,我對R不是很精通,但我有一個100個節點的網絡,我正在做分析。 我想找到網絡中每對節點之間的所有最短路徑(100次計算),訣竅是將它們作為整數返回,路徑長度如果你願意的話。
#construct a small sample of the graph
g = graph.formula('insert graph')
#use the function to retrieve shortest paths from a single vertex
get.all.shortest.paths(g, 1, to = V(g))
#output
$res
$res[[1]]
[1] 1
$res[[2]]
[1] 1 2
$res[[3]]
[1] 1 2 3
$res[[4]]
[1] 1 2 3 4
$res[[5]]
[1] 1 2 3 4 5
$res[[6]]
[1] 1 10 9 8 7 6
$res[[7]]
[1] 1 2 3 4 5 6
$res[[8]]
[1] 1 10 9 8 7
$res[[9]]
[1] 1 10 9 8
$res[[10]]
[1] 1 10 9
$res[[11]]
[1] 1 10
$nrgeo
[1] 1 1 1 1 1 2 1 1 1 1
雖然這很好,但手動迭代所有100個節點是不切實際的。 有沒有辦法實現自動化? 我的問題的第二個組成部分是我希望將每個路徑輸出為數字,如路徑長度,而不是給出實際路徑。 我想要的另一件事是計算模式路徑長度(或在網絡中更常見的路徑長度)。 查看100個數字是不可行的,因此必須自動化。
任何幫助都會被徹底欣賞,這似乎是一個新手的問題,我有點像新手用戶。
您可以使用shortest.paths
返回每個節點之間距離的矩陣:
distMatrix <- shortest.paths(g, v=V(g), to=V(g))
結果:
cdc42 ste20 mkk2 bul1 mth1 vma6 vma2 ...
cdc42 0 1 Inf Inf 4 3 2
ste20 1 0 Inf Inf 3 2 1
mkk2 Inf Inf 0 1 Inf Inf Inf
bul1 Inf Inf 1 0 Inf Inf Inf
mth1 4 3 Inf Inf 0 1 2
vma6 3 2 Inf Inf 1 0 1
vma2 2 1 Inf Inf 2 1 0
...
它很容易訪問它:
# e.g. shortest path length between the second node and the fifth
distMatrix[2,5]
>
[1] 3
# or using node names:
distMatrix["ste20", "mth1"]
>
[1] 3
如果你只想要長度,你應該使用path.length.hist
。 要獲得該模式,只需使用
which.max(path.length.hist(g)$res)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.