A Plot of 250 Random Walks

July 22, 2011
By

[This article was first published on mickeymousemodels, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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")
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:

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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.



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

Sponsors

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)