[R] Alternative to apply in base R

Charles C. Berry ccberry at ucsd.edu
Tue Nov 8 17:55:02 CET 2016

On Tue, 8 Nov 2016, Doran, Harold wrote:

> Without reaching out to another package in R, I wonder what the best way is to speed enhance the following toy example? Over the years I have become very comfortable with the family of apply functions and generally not good at finding an improvement for speed.
> This toy example is small, but my real data has many millions of rows 
> and the same operations is repeated many times and so finding a less 
> expensive alternative would be helpful.
> mm <- matrix(rnorm(100), ncol = 10)
> rn <- apply(mm, 1, prod)

If the real example has only 10 columns, try this:

> y <- mm[,1]
> for (i in 2:10) y[] <- y*mm[,i]
> all.equal(y,rn)

If it has many more columns, I would `reach out' to the inline package and 
write 3 lines of C or Fortran to do the operation.



More information about the R-help mailing list