by jacobolus · 14y ago · 0 comments
I’d rewrite this example as something like:
num.steps <- 1000
num.walks <- 100
step.std.dev <- 0.03
start.value <- 15
rand.row <- function() rnorm(num.steps, 1, step.std.dev)
walk <- function () cumprod(rand.row()) * start.value
all.walks <- t(replicate(100, walk()))
plot(colMeans(all.walks), type = "l")
[I’m not an R guy, so that might not be the most typical style ever, but you get the idea...]For example:
replicate(2, rnorm(2))
creates a 2x2 matrix of independent random values. Whereas: x <- rnorm(2)
replicate(2, x)
Instead creates a 2x2 matrix with a single random value for each row, repeated across all columns. And so if you want to decompose it, you need to do: x <- function() rnorm(2)
replicate(2, x())
Which will re-call x twice inside the replicate function. replicate <- function (n, expr, simplify = TRUE)
sapply(integer(n),
eval.parent(
substitute(function(...) expr)),
simplify = simplify)
The replicate function uses R's compute-on-the-language to construct a new function that has expr as its body.A closure's argument will be evaluated at most once.
The way he did it is nice and minimal, and in 2 months when you go back to change something you will have no idea what you did.
I've had to do a few things in R and I always dread revisiting my code. Half the time it's easier and faster to just rewrite everything.