[R] Idiom for column operations?
Prof Brian Ripley
ripley at stats.ox.ac.uk
Wed Oct 27 08:09:48 CEST 2004
On Tue, 26 Oct 2004, Rob Steele wrote:
> Is there a better way to express operations between matrices and column
> vectors than transposing the matrix twice?
> This is the kind of thing I'm talking about:
> m = matrix(1:20, 3, 4)
Ouch: that gives a warning as 20 > 3*4.
> v = colSums(m)
> t(t(m) / v) ## <-- kinda ugly, ain't it?
> I thought of converting the column vector to a matrix:
> m / matrix(v, nrow = nrow(m), ncol = length(v), byrow = TRUE)
> But that seems even worse.
Use the fact that matrix/vector is done as vector/vector and matrices are
stored down columns:
You will find that (or using other variants on rep) in lots of S/R code.
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 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help