# A Plot of 250 Random Walks

July 22, 2011
By

(This article was first published on mickeymousemodels, and kindly contributed to R-bloggers)

For some reason I feel like plotting some random walks. Nothing groundbreaking, but hopefully this post will be useful to someone. Here’s my R code:

`# Generate k random walks across time {0, 1, ... , T}T <- 100k <- 250initial.value <- 10GetRandomWalk <- function() {  # Add a standard normal at each step  initial.value + c(0, cumsum(rnorm(T)))}# Matrix of random walksvalues <- replicate(k, GetRandomWalk())# Create an empty plotdev.new(height=8, width=12)plot(0:T, rep(NA, T + 1), main=sprintf("%s Random Walks", k),     xlab="time", ylab="value",     ylim=10 + 4.5 * c(-1, 1) * sqrt(T))mtext(sprintf("%s%s} with initial value of %s",              "Across time {0, 1, ... , ", T, initial.value))for (i in 1:k) {  lines(0:T, values[ , i], lwd=0.25)}for (sign in c(-1, 1)) {  curve(initial.value + sign * 1.96 * sqrt(x), from=0, to=T,        n=2*T, col="darkred", lty=2, lwd=1.5, add=TRUE)}legend("topright", "1.96 * sqrt(t)",       bty="n", lwd=1.5, lty=2, col="darkred")savePlot("random_walks.png")`

Just to be clear, these are one-dimensional random walks, in discreet time, and all I’m doing is taking cumulative sums of standard normals. The goal is to end up with a nice plot:

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...