0

I'm running the random walk function in R using iGraph, where my random walker is traveling along a road network. However, when I run the below code I find that the random walker always goes back to the same vertices/nodes. Is there a way I can program the random walker to follow a new path each time?

    set.seed(1)
    resample <- function(x, ...) x[sample.int(length(x), ...)]
    n <- 1000
    tm <- G
    x = sub$idNode1[sample(1:length(sub$idNode1),1)]

    start <- x # Random walk starting vertex
    len <- 100 # Walk length
    path <- c(start, rep(NA, len))
    for(i in 2:(len + 1)) {
        idx <- G[path[i - 1], ] != 0
        if(any(idx)) {
            path[i] <- resample(which(idx), 1, prob = G[path[i - 1], idx])
        } else {
          break # Stopping if we get stuck
        }
Yaya
  • 1
  • 3
  • Your example seems to miss a few things, like `G`. It would be helpful if you could make the code complete and reproducible. – AkselA Jul 18 '18 at 10:50
  • @AkselA - I'm not sure if I can share my whole graph data frame. But basically, it's a road network made up of Node 1, Node 2, and weight (distance between them). The output is showing me the path that is traveled (Node id). From what I understand about the random walker function is that the next step is independent from the previous step ie. it can return to the same node. I want to avoid a circular path. Any help would be greatly appreciated :) – Yaya Jul 18 '18 at 12:36
  • 1
    A (maybe naïve) approach could be to simply keep a record of all the nodes your random walker visits, and for each step it makes check if the new node already exist in the record. If it doesn't, proceed as normal, if it does, try again. Note that this can easily result in dead ends (it's a variant of the [Seven Bridges of Königsberg](https://en.wikipedia.org/wiki/Seven_Bridges_of_Königsberg) problem) – AkselA Jul 18 '18 at 14:25

0 Answers0