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) 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. Thanks! Rob Steele
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) > 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. > > Thanks! > Rob Steele >Rob, Would ?sweep be sufficient for you? m <- matrix(1:20, 5, 4) sweep(m, 2, colSums(m), "/") --sundar
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: m/rep(v, each=nrow(m)) 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