Search code examples
rloopsrandom-walk

How do I include a step counter in a random walk?


In my random walk loop I need to incorporate a function that uses the step number as a variable.

How do I get R to produce a step number (loop counter may be a better term) during a random walk?

I need it right at the end of this code where I currently have the dummy code step.num

For reference my random walk code is:

    walkW <- function(n.times=125,
               xlim=c(524058,542800),
               ylim=c(2799758,2818500),
               start=c(542800,2815550),
               stepsize=c(4000,4000)) {

    plot(c(0,0),type="n",xlim=xlim,ylim=ylim,
           xlab="Easting",ylab="Northing",col="white",col.lab="white")#arena 
    x <- start[1]
    y <- start[2]
    steps <- 1/c(1,2,4,8,12,16)
    steps.y <- c(steps,-steps,0)
    steps.x <- c(steps[c(1,5,6)],-steps,0)
    points(x,y,pch=16,col="green",cex=1)

for (i in 1:n.times) {
        repeat {
           xi <- stepsize[1]*sample(steps.x,1)
           yi <- stepsize[2]*sample(steps.y,1)
           newx <- x+xi
           newy <- y+yi
           if (newx>xlim[1] && newx<xlim[2] &&
               newy>ylim[1] && newy<ylim[2]) break
        }
        lines(c(x,newx),c(y,newy),col="white")
         x <- newx
           y <- newy
}
  step.num<-(your magical step counter function) #I need the step counter here
 }

set.seed(101)
walkW(s)

Solution

  • After a for loop that was "broken", the index variable persists, so your magical code would just be:

     step.num <- i
    

    Although for-loops are technically functions, sometimes they seem to have different scoping rules, and this is one such time. Your function returns the 'step.num' value, and after exit from walkW, you would not have been able to access 'i', but if the for-loop were done in the .GlobalEnv then the index "i" would still not have been reset or NULL-ed when the for-loop ended via break.