# [R] 2D Random walk

Patrick Burns pburns at pburns.seanet.com
Thu Dec 2 17:51:41 CET 2010

```Hopefully someone has a good suggestion
for your question.  I'd just like to
point out that the generation of the
random walk is pretty much optimized for
worst performance.

A 'for' loop is not necessary and growing
the objects could be a very significant
drag.  See Circles 2 and 3 of 'The R Inferno'.

Hint: 'cumsum' will be useful.

On 02/12/2010 15:58, featherbox 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")
>

--
Patrick Burns
pburns at pburns.seanet.com
http://www.portfolioprobe.com/blog
http://www.burns-stat.com
(home of 'Some hints for the R beginner'
and 'The R Inferno')

```