# [R] 2D Random walk

featherbox morefunkythangrooovy at hotmail.com
Thu Dec 2 16:58:29 CET 2010

```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.

```