【发布时间】:2014-10-30 06:59:15
【问题描述】:
在我的随机游走循环中,我需要合并一个使用步数作为变量的函数。
如何让 R 在随机游走期间生成步数(循环计数器可能是更好的术语)?
我在这段代码的末尾需要它,我目前有虚拟代码 step.num
作为参考,我的随机游走代码是:
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)
【问题讨论】:
-
您可能还喜欢
all函数。你的中断条件可以重写if (all(newx > xlim[1], newx < xlim[2], newy > ylim[1], newy < ylim[2])),这样更容易阅读。 -
你们俩都很棒。实际上,我只是突然回来提供相同的答案。当魔法像 x=y 一样简单时,它总是很棒。非常感谢!
标签: r loops random-walk