Some random walk fun. I use 400 steps in each example.
A random walk using a recursive equation.
A random walk using R’s “cumsum” command. Here, I will generate a vector of randomly selected 1’s and -1’s. “Cumsum” then compiles those values.
Now for the real fun. Here, the walk can move forward (1) or backward (-1) along either dimension 1 or 2. So, if the walk moves forward (1) in dimension 1, dimension 2 receives a value of 0 for that step. If the walk moves backward (-1) in dimension 2, dimension 1 receives a 0 for that step.
The “index” merits some explaining. The walk will randomly choose to move in dimension 1 (column 1 in “rw_3”) or 2 (column 2 in “rw_3”). This index establishes a way of assigning which choice the walk makes. Here is what “index” looks like:
head(index)
[,1] [,2]
[1,] 1 1
[2,] 2 1
[3,] 3 1
[4,] 4 2
[5,] 5 1
[6,] 6 1
The first column values tell the random walk which step its on (i.e., which row in “rw_3”), and the second column values tell the random walk which dimension it will step through (i.e., which column in “rw_3”).
So the “index” represents a random selection of dimension 1 or 2 at each step. Now I can apply that random choice to the random choice of stepping forward or backward (1 or -1).
# At each step, select a dimension (specified by the index; column 1 or 2 of rw_3)
# Then randomly select forward or backward
rw_3[index] <- sample(c(-1, 1),
400,
replace = T)
# Now sum each column (dimension) just like our 1-dimensional walks
rw_3[,1] <- cumsum(rw_3[,1])
rw_3[,2] <- cumsum(rw_3[,2])
Here is a visualization of the walk:
Bo\(^2\)m =)