I would like to implement a simulation program, which requires the following structure:
It has a for loop, the program will generate an vector in each iteration. I need each generated vector is appended to the existing vector.
I do not how how to do this in R. Thanks for the help.
These answers work, but they all require a call to a non-deterministic function like
sample()in the loop. This is not loop-invariant code (it is random each time), but it can still be moved out of theforloop. The trick is to use thenargument and generate all the random numbers you need beforehand (if your problem allows this; some may not, but many do). Now you make one call rather thanncalls, which matters if yournis large. Here is a quick example random walk (but many problems can be phrased this way). Also, full disclosure: I haven’t had any coffee today, so please point out if you see an error 🙂We can rewrite this with one call to
sample():Proof of speed increase (n=10000):
If your simulation needs just one random variable per simulation function call, use
sapply(), or better yet themulticorepackage’smclapply(). Revolution Analytics’sforeachpackage may be of use here too. Also, JD Long has a great presentation and post about simulating stuff in R on Hadoop via Amazon’s EMR here (I can’t find the video, but I’m sure someone will know).Take home points:
numeric(n)orvector('list', n)forloops. Cleverly push stochastic functions out of code with theirnargument.sapply()orlapply(), or better yetmclapply.x <- c(x, rnorm(100)). Every time you do this, a member of R-core kills a puppy.