如何从igraph R连接最短路径

时间:2018-10-10 22:41:42

标签: r igraph

如何连接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)

2 个答案:

答案 0 :(得分:1)

以下是使用游程编码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

答案 1 :(得分:1)

如果您命名,那么事情总是容易的

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