Skip to content
Prev 246522 / 398502 Next

speed up in R apply

On Wed, Jan 5, 2011 at 1:22 PM, David Winsemius <dwinsemius at comcast.net> wrote:
Hmm.  Not sure that would help, David.  You could use a matrix
multiplication of a %*% rep(1, ncol(a)) if you wanted the row sums but
of course you could also use rowSums to get those.
To expand a bit on David's point, the apply function isn't magic.  It
essentially loops over the rows, in this case.  By multiplying columns
together you are performing the looping over the rows in compiled
code, which is much, much faster.  If you want to do this kind of
operation effectively in R for a general matrix (i.e. not knowing in
advance that it has exactly 5 columns) you could use Reduce
user  system elapsed
   0.15    0.09    0.37
user  system elapsed
 22.090   0.140  22.902
[1] TRUE
user  system elapsed
  0.410   0.010   0.575
[1] TRUE