[R] 2D Random walk

jim holtman jholtman at gmail.com
Thu Dec 2 18:33:07 CET 2010


Here is a use of color to show what the path is and following up on
Patrick's post to make the code a little more efficient:

# compute path
n <- 10000
rw <- matrix(0, ncol = 2, nrow = n)
# generate the indices to set the deltas
indx <- cbind(seq(n), sample(c(1, 2), n, TRUE))

# now set the values
rw[indx] <- sample(c(-1, 1), n, TRUE)
# cumsum the columns
rw[,1] <- cumsum(rw[, 1])
rw[, 2] <- cumsum(rw[, 2])

plot(0,type="n",xlab="x",ylab="y",main="Random Walk Simulation
In Two Dimensions",col=1:10,xlim=range(rw[,1]),ylim=range(rw[,2]))

# use 'segments' to color each path
segments(head(rw[, 1], -1)
       , head(rw[, 2], -1)
       , tail(rw[, 1], -1)
       , tail(rw[, 2], -1)
       , col = rainbow(nrow(rw) -1)  # a range of colors
       )

end<-cbind(rw[10000,1],rw[10000,2])
start<-cbind(0,0)

points(start,pch=16,col="green", cex = 3)
points(end,pch=16,col="red", cex = 3)



On Thu, Dec 2, 2010 at 10:58 AM, featherbox
<morefunkythangrooovy at hotmail.com> wrote:
>
> I've wrote some code to simulate a random walk in 2 dimensions on a lattice.
> Basically I want to add something in to make it plot it point by point so
> you can see what is going on.
> Heres my code for the random walk in 2d
>
>
> RW2D<-function(N)
>  {
>    i<-0
>    xdir<-0
>    ydir<-0
>    xpos<-vector()
>    xpos[1]<-xdir
>    ypos<-vector()
>    ypos[1]<-ydir
>    for (i in 1:N-1)
>      {
>        r<-runif(1)
>        if(r<=0.25) {xdir<-xdir+1}
>        if(r>0.25 && r<=0.5) {xdir<-xdir-1}
>        if(r>0.5 && r<=0.75) {ydir<-ydir +1}
>        if(r>0.75) {ydir<-ydir-1}
>        xpos[i+1]<-xdir
>        ypos[i+1]<-ydir
>      }
>    return(cbind(xpos,ypos))
>  }
> rw<-RW2D(10000)
>
> xmin<-min(rw[,1])
> xmax<-max(rw[,1])
> ymin<-min(rw[,2])
> ymax<-max(rw[,2])
>
> plot(rw[,1],rw[,2],type="l",xlab="x",ylab="y",main="Random Walk Simulation
> In Two Dimensions",col="green4",xlim=range(xmin:xmax),ylim=range(ymin:ymax))
>
> end<-cbind(rw[10000,1],rw[10000,2])
> start<-cbind(0,0)
>
> points(start,pch=4,col="red")
> points(end,pch=4,col="red")
>
> --
> View this message in context: http://r.789695.n4.nabble.com/2D-Random-walk-tp3069557p3069557.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list