This short post is to share an R tip Pierre recently gave me. When you need to store values sequentially (typically inside a loop), it’s more far efficient to create the whole vector (or matrix) and to fill it, rather than to concatenate the values to your current vector (or matrix). In terms of allocation time, it’s up to 60 times faster
n=10^5 a=NULL system.time(for (i in 1:n){a=c(a,1)}) >utilisateur système écoulé > 12.09 0.00 12.09 b=rep(0,n) system.time(for (i in 1:n){b[i]=1}) >utilisateur système écoulé > 0.21 0.00 0.20
which makes a big difference. In a Gibbs sampling loop, where a lot of other computations are done, I still have gain of 25%! For other recommendations (don’t use parentheses where you can avoid them), you can have a look on this post.
This could be added to the R programming wikibook, a collaborative handbook for R : http://en.wikibooks.org/wiki/R_Programming/ in the advanced programming page http://en.wikibooks.org/wiki/R_Programming/Advanced_programming
Thanks for that link, I’m often looking for help online.