r - 我如何对随机游走设置竞技场限制?

标签 r random-walk

我正在构建一个有偏相关的随机游走,并且我已经设法构建了 RW,并将其偏向西风运动。

问题:我需要将步行固定在一侧(或所有)侧。

目前的代码是:

walk<-function(n.times){ 
   plot(524058:542800,2799758:2818500,type="n",
      xlab="Easting",ylab="Northing")#aren‌​a 
      y<-2815550 ##startY 
      x<-542800 #startX
      N<-4000
      E<-4000
      points(x,y,pch=16,col="red",cex=1)
      for (i in 1:n.times) {
          yi <- sample(c(N,N/2,N/4,N/8,N/12,N/16,
                      0,-N,-N/2,-N/4,-N/8,-N/12,-N/16),1)      
          xi<-sample(c(E,E/12,E/16, 0,-E,-E/2,-E/4,-E/8,-E/12,-E/16),1)       
          lines(c(x,x+xi),c(y,y+yi),col="blue")
          x<-x+xi
          y<-y+yi 
      }
   }
   iterations<-125 
   walk(iterations) 

到目前为止,我最接近的是使用
 if(y>2818500 | y<2799758 | x>542800 | x<524058)  break 

如果它离开竞技场,它只会停止步行。

最佳答案

该函数的一个稍微清理过的版本:主要的变化是增加了一个 repeat {}循环将重新选择步骤,直到新位置在限制范围内(也可以使用 while() {} 循环)。

更新 : 没有仔细阅读问题陈述,忘记了偏见。此代码以与 OP 代码相同的方式包含偏差。对于 N-S 运动,平均步长为 0;对于 E-W 运动,通过忽略一些积极的步骤可能性,我们得到 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)

enter image description here

关于r - 我如何对随机游走设置竞技场限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26390127/

相关文章:

r - 查看包中是否存在变量/函数?

r - 将来自 Quantstrat 的订单簿写入 CSV 文件

javascript - 在 JavaScript 中生成平滑的随机趋势(Random Walk)

Python:醉汉的行走

r - 如何生成 SVG 格式的二维码?

r - 如何告诉 ggplot2 使用用户创建的比例来获得新的美感。

r - 如何在 R 中连接/组合函数?

c++ - 初学者 C++ - 带有奇怪 setw 错误的简单随机游走程序

c - 10X10 数组中的随机游走