Friday 15 July 2011

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



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

in random walk loop need incorporate function uses step number variable.

how r produce step number (loop counter may improve term) during random walk?

i need right @ end of code have dummy code step.num

for reference 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) (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 step counter here } set.seed(101) walkw(s)

after loop "broken", index variable persists, magical code be:

step.num <-

although for-loops technically functions, seem have different scoping rules, , 1 such time. function returns 'step.num' value, , after exit walkw, not have been able access 'i', if for-loop done in .globalenv index "i" still not have been reset or null-ed when for-loop ended via break.

r loops random-walk

No comments:

Post a Comment