# [R] 2D Random walk

jim holtman jholtman at gmail.com
Sun Jul 3 02:40:21 CEST 2011

```This should work.  You have to return an object from a function; you
can not try to reference an object within a function.  So the value is
returned and saved in an object called 'rw' since that is how you are
referening it.

walk.2d<-function(n)
{
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])

rw  # return value
}
n<-1000

rw <- walk.2d(n)
plot(0, type="n",xlab="x",ylab="y",main="Random Walk Simulation In
Two Dimensions",xlim=range(rw[,1]),ylim=range(rw[,2]))

# use 'segments' to color each path
2], -1), col ="blue")

On Wed, Jun 29, 2011 at 11:30 AM, Komal <Komalsharif86 at gmail.com> wrote:
> HI Jholtman,
>
> walk.2d<-function(n)
> {
> 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])
>
> return(rw[,1],rw[,2])
> }
> n<-1000
>
> plot(walk.2d(n), type="n",xlab="x",ylab="y",main="Random Walk Simulation In
> Two Dimensions",xlim=range(rw[,1]),ylim=range(rw[,2]))
>
>        # use 'segments' to color each path
> 2], -1), col ="blue")
>
> I tried to make it in a function.. its not working I dont know why... please
> help me correcting this code.
>
> --
> View this message in context: http://r.789695.n4.nabble.com/2D-Random-walk-tp3069557p3633205.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
> and provide commented, minimal, self-contained, reproducible code.
>

--
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?

```