[R]:?alternative to loop

Prof Brian D Ripley ripley at stats.ox.ac.uk
Wed May 3 14:41:08 CEST 2000


On Wed, 3 May 2000, Uwe Ligges wrote:

> nicolas baurin wrote:
> > for the application of a function to each column of a matrix (ex:
> > function sum()), i'd like to know if there is a simpler (and faster)
> > alternative to a loop like :
> > 
> > for (i in 1: ncol(m)){sum(m[i])}
> 
> This will not work in any way, I suppose.
> If you want to simplify something like
>  
>  s <- NULL
>  for (i in 1: ncol(m)){ s[i] <- sum(m[,i])}
> 
> you should try
> 
>  s <- apply(m, 2, sum) 
> 
> 
> Have a look in documentation to apply(.) !

Right, but in this case it is matrix multiplication, so try

drop(rep(1,nrow(m)) %*% m)

which is much faster on a large matrix (because it uses less memory).
There are lots of tricks of that sort.  Often something like

unlist(lapply(split(m, col(m)), sum))

is faster still.  (These things change: lapply was sped-up for 1.0.0, but
the comparable change in apply was not put in, and we should pursue it.)

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list