繁体   English   中英

如何从igraph R连接最短路径

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM