A Plot of 250 Random Walks

July 22, 2011

(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 <- 100
k <- 250
initial.value <- 10
GetRandomWalk <- function() {
# Add a standard normal at each step
initial.value + c(0, cumsum(rnorm(T)))
# Matrix of random walks
values <- replicate(k, GetRandomWalk())
# Create an empty plot
dev.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")

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:

To leave a comment for the author, please follow the link and comment on their blog: mickeymousemodels.

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...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)