0

在我之前的问题中:如何对随机游走设置竞技场限制? 社区帮助在设定的竞技场中创建了随机游走功能。此功能旨在模拟一条鱼在一个区域中移动,但现在我需要让它决定何时在满足某个条件时停止。

我认为它就像 {{if(z>P)break}}放在循环函数之前一样简单。我希望它理解的是“如果满足此条件,则停止,否则继续前进,直到达到最大步数。

相反,它导致我的随机游走变得确定性(我总是得到相同的路径,并且它永远不会在 step.max 之前停止)。

主要问题:如果 z>P,我如何告诉随机游走停止?

以供参考:

step.max<-125
step.prob<-function(n.times=step.max){
draw=sample(0:100,1,replace=T)
CS<-sample(draw,size=1,replace=TRUE)
CS.max<-100
step.num<-15
SP<-((CS/CS.max)*(1-(step.num/step.max))+(step.num/step.max))*100
if(SP>P){stop('Settled at step number',P)}else{SP
     }
}
z<-step.prob(1) #renaming the above function to be easier to reference later
P<-80 #preset cutoff point for value z, ranges from 0-100
walkE <- function(n.times=125,
               xlim=c(524058,542800),
               ylim=c(2799758,2818500),
               start=c(525000,2810000),
               stepsize=c(4000,4000)) {
    plot(c(0,0),type="n",xlim=xlim,ylim=ylim,
           xlab="Easting",ylab="Northing") 
    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,-steps[c(1,5,6)],0)
    points(x,y,pch=16,col="red",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="blue")
        x <- newx
        y <- newy
if(z>P){stop(points(newx,newy,col="green",cex=1))} 
                        #this is where I want it to stop if z>P
         else
if(z<P){points(newx,newy,pch=1,col="blue",cex=1)}
    else
if(step.max){points(newx,newy,pch=16,col="green",cex=1)}
set.seed(101)}
}
walkE(step.max) #run above random walk function walkE looped for the step.max number

提前致谢!!!

4

1 回答 1

0

这很容易,可以通过stop(...)在用户定义的step.prob函数中插入一个函数来完成。

step.prob<-function(n.times=step.max, p){
  draw=sample(0:100,1,replace=T)
  CS<-sample(draw,size=1,replace=TRUE)
  CS.max<-100
  CS.max
  step.num<-15
  SP<-((CS/CS.max)*(1-(step.num/step.max))+(step.num/step.max))*100
  if(SP > p) {
    stop('Your random walk exceeded ', p)
  } else {
  SP
  }
}

如果这对您不起作用,请查看break命令。

因此,当随机游走值 > p 时:

step.prob(p=300000)
# Error in step.prob(p = 3) : Your random walk exceeded 3

如果你想将函数返回的值设置为 p 你可以在命令SP <- p之前添加。stop

于 2014-10-16T23:41:30.000 回答