[R] Functions on matrix row level

Prof Brian D Ripley ripley at stats.ox.ac.uk
Mon Jan 28 16:30:22 CET 2002


On Mon, 28 Jan 2002, Arndt, Ulrich, VF-VP wrote:

> Hi together,
>
> I have some data in a matrix structure - say 1000 rows with 10 columns. And
> I like to do some calculations (like max, avg or min) on row level.
> The only solution I found so fare was using a loop like
>
> for (i in 1:1000) {
>        max[i]  <- max(matrix[I,])
> }
>
> It looks like that this is not very fast.

Only 0.12 secs on my machine.  You did set max to numeric(1000) first?

> Does an other way exists?

More comprehensible, but not necessarily much faster is

mymax <- apply(mymatrix, 1, max)

(0.03 secs)

Try to avoid confusing people (and perhaps R) by calling objects the same
name as system ones (max, matrix).

For average, rowMeans in R-devel is much faster still, if you need to save
another 0.03 seconds ....

-- 
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