![](/img/trans.png)
[英]igraph in R: error with get.shortest.paths but not with shortest.paths
[英]How to concatenate shortest paths from igraph R
如何連接igraph的兩個最短路徑響應,以使它們形成一條路徑? 即
set.seed(6857)
g <- sample_smallworld(1, 100, 5, 0.05) #Building a random graph
sp <- get.shortest.paths(g, 5, 70, output = "both")
sp1 <- get.shortest.paths(g, 70, 80, output = "both")
然后是這樣的:
sp <- c(sp,sp1)
這樣我最終得到了sp和sp1相同的格式,但是將它們連接在一起。
另外:我需要它,以便第一個路徑的結尾是第二個路徑的開頭。 因此,理想情況下,它們串聯在一起時就不會有復制。 因此,如果頂點為c(5 1 75 70, 70 75 80)
,則結果為c( 5 1 75 70 75 80)
這是使用游程編碼rle
的解決方案:
> combined <- c(as.numeric(sp$vpath[[1]]),as.numeric(sp1$vpath[[1]]))
> combined
[1] 5 1 75 70 70 75 80
> x <- combined[cumsum(rle(as.character(combined))$lengths)]
> x
[1] 5 1 75 70 75 80
如果您命名自己的頂點,事情總是容易的
set.seed(6857)
g <- sample_smallworld(1, 100, 5, 0.05) #Building a random graph
V(g)$name = 1:vcount(g)
sp <- get.shortest.paths(g, 5, 70, output = "both")
sp1 <- get.shortest.paths(g, 70, 80, output = "both")
列表中的每個元素都可以與c
結合在一起,只要它們來自同一圖即可。 節點列表可以與同一圖的其他節點列表組合,並且邊緣列表可以與同一圖的其他邊緣列表組合
sp2 <- lapply(setNames(names(sp), names(sp)), function(x){
temp <- c(sp[[x]][[1]], sp1[[x]][[1]])
if(x == 'vpath'){
newVPath <- temp$name %>%
rle %>%
.$values %>%
as.character()
return(V(g)[newVPath])
}
return(temp)
})
應該給你:
$vpath
+ 6/100 vertices, named, from 94d5cf0:
[1] 5 1 75 70 75 80
$epath
+ 5/500 edges from 94d5cf0 (vertex names):
[1] 1-- 5 1--75 70--75 70--75 75--80
$predecessors
NULL
$inbound_edges
NULL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.