简体   繁体   中英

How to concatenate shortest paths from igraph R

How do I concatenate two shortest path responses from igraph so that they make one path? ie

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")

then something like:

sp <- c(sp,sp1)

So that I end up with the same formatting of sp and sp1 but have them joined together.

Additional: I need it so that the end of the first path is the beginning of the second path. So ideally there would be no replication when they concatenate. So if the vertices are c(5 1 75 70, 70 75 80) this would result in c( 5 1 75 70 75 80)

Here is a solution using run length encoding 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

Things are always easier if you name you name your vertices

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")

Each element of the list can be joined together with c as long as they're from the same graph. Nodelists can be combined with other nodelists of the same graph and edge lists can be combined with other edgelists of the same graph

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)
})

should give you:

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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