简体   繁体   English

如何在随机行走中包括计步器?

[英]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? 在随机游走期间,如何获得R以产生步数(循环计数器可能是一个更好的术语)?

I need it right at the end of this code where I currently have the dummy code step.num 我需要在代码末尾的地方,目前我有虚拟代码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)

After a for loop that was "broken", the index variable persists, so your magical code would just be: 在“中断”的for循环之后,索引变量仍然存在,因此您的神奇代码将是:

 step.num <- i

Although for-loops are technically functions, sometimes they seem to have different scoping rules, and this is one such time. 尽管for循环在技术上是功能,但有时它们似乎具有不同的作用域规则,而这正是一次。 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 . 您的函数返回'step.num'值,从walkW退出后,您将无法访问'i',但是如果在.GlobalEnv中完成了for循环,则索引“ i”仍然不会当for循环通过break结束时,已被重置或置为NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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