[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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