Friday, August 7, 2009

Random walk in R



This post is just an excuse for me to put up what I thought is a cool graphic. It's the progress of a set of 10 independent random walks, with equal probability of going up or down at each step, and the progress is plotted using R. This is probably not the right way to do it in R. I often have trouble when I want to do something that seems like it should use individual values rather than vectors. Anyway, here goes.

• in the first part, we just set the random number generator, the number of steps N, and set up a plot with type = 'n' so that it makes an empty plot of the right size but doesn't actually plot anything yet.

• next, we get the colors for each of the 10 individual walks and set up a source for the steps. One should be able to just do sample(c(-1,1), replace=T), but I wasn't happy with the distributions I got. I don't know if it's really a difference.

• in the main part we have an outer loop that goes through the walks, and an inner loop that does the steps. The line where I do y = sum(y,d) is the weird part. y = y + d didn't work. Then we just plot points and lines in the usual way. If you're unsure about the arguments just do ?points or ?lines.

set.seed(5)
N = 60
plot(1:10,xlim=c(0,N),
ylim=c(-18,18),type='n')

color.list = rainbow(10)
L = c(rep(-1,1000),
rep(1,1000))

for (j in 1:10) {
y = 0
for (i in 1:N) {
d = sample(L,1,replace=T)
y0 = y
y = sum(y,d)
points(i,y,pch=16,
cex=1.5,col=color.list[j])
lines(c(i-1,i),c(y0,y),
lwd=2,col=color.list[j])
}}