该函数的稍微清理版本:主要变化是添加了repeat {}
循环将重新选择步骤,直到新位置在限制内(也可以使用while() {}
loop).
update:没有仔细阅读问题陈述,忘记了偏见。该代码以与 OP 代码相同的方式包含了偏差。对于 N-S 运动,平均步长为 0;对于东西向运动,通过忽略一些积极步骤的可能性,我们得到mean(steps.x)
等于-0.0875;由于步骤可能性是均匀采样的,因此步行平均向左漂移0.0875*stepsize[1]
每步的单位。
walk <- function(n.times=125,
xlim=c(524058,542800),
ylim=c(2799758,2818500),
start=c(542800,2815550),
stepsize=c(4000,4000)) {
## blank plot of arena
plot(c(0,0),type="n",xlim=xlim,ylim=ylim,
xlab="Easting",ylab="Northing")
## extract starting point
x <- start[1]
y <- start[2]
## define potential step sizes
steps <- 1/c(1,2,4,8,12,16)
## all possible positive or negative steps for N-S movement
steps.y <- c(steps,-steps,0)
## bias E-W movement by leaving out some positive steps
steps.x <- c(steps[c(1,5,6)],-steps,0)
## plot starting location
points(x,y,pch=16,col="red",cex=1)
for (i in 1:n.times) {
repeat {
## pick jump sizes
xi <- stepsize[1]*sample(steps.x,1)
yi <- stepsize[2]*sample(steps.y,1)
## new candidate locations
newx <- x+xi
newy <- y+yi
## IF new locations are within bounds, then
## break out of the repeat{} loop (otherwise
## try again)
if (newx>xlim[1] && newx<xlim[2] &&
newy>ylim[1] && newy<ylim[2]) break
}
lines(c(x,newx),c(y,newy),col="blue") ## draw move
## set new location to candidate location
x <- newx
y <- newy
}
}
set.seed(101)
walk(1000)