# Thread: Random Walk in 2D

1. ## Random Walk in 2D

I want to write a program to simulate a Simple Random walk in 2D, but I don't really have any similar code to look at for help. Would like to use R but can't seem to find any resourses for that. Everything seems to be in C++ etc.
Fortran 90 could also be an option. Using gnuplot to plot graphs.
Can anyone help me out?
Thanks.

2. Something like

Code:
rw <- function(n){
y <- numeric(n)
for (i in 1:(n-1)){
y[i+1] <- y[i]+rnorm(1)
}
plot(y, type="l")
}

Will create a function that will plot a random walk with initial level of 0, and steps that are IID normal(0,1) in R

3. But is that code not for a 1-dim walk?
Would I have to use a 2d vector (x,y) that goes to (x+1,y) when then move right, (x-1) for left, (x,y+1) for up and (x,y-1) for down?
I could generate a random number from the U[0,1] distribution to decide which step left,right,up,down to take.

Is this along the right lines?

Code:
rw <- function(n){
y <- data.frame(numeric(n),numeric(n))
for (i in 1:(n-1)){
y[i+1,1] <- (y[i,1]+rnorm(1))
y[i+1,2] <- y[i,2]+rnorm(1)
}
plot(y, type="l")
}
Or if you were after discrete steps +1 or -1
Code:
rw <- function(n){
y <- data.frame(numeric(n),numeric(n))
for (i in 1:(n-1)){
y[i+1,1] <- (y[i,1]+ (ifelse(runif(1)<.5,1,-1)))
y[i+1,2] <- y[i,2]+(ifelse(runif(1) <.5,1,-1))
}
plot(y, type="l")
}