[R] simple matrix division.

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Sep 2 21:36:55 CEST 2006


On Sat, 2 Sep 2006, Alexander Nervedi wrote:

> Hi
> 
> I have
> 
> >x<-matrix(c(1,2,3,4), ncol = 2)
> >x
>      [,1] [,2]
> [1,]    1    3
> [2,]    2    4
> 
> I'd like these two be divided by their column totals. so 1/3 and 2/3 and 3/7 
> and 4/7. The obvious
> >x/colSums(x)
>           [,1]      [,2]
> [1,] 0.3333333 1.0000000
> [2,] 0.2857143 0.5714286
> 
> gives me the wrong results for off diagnal ones,  since it divides the first 
> row by 3 and second by 7. The inelegant
> >t(t(x)/colSums(x))
>           [,1]      [,2]
> [1,] 0.3333333 0.4285714
> [2,] 0.6666667 0.5714286
> 
> gives me the right thing. I was wondering if there is any better way of 
> getting what I want.

x/rep(colSums(x), each = nrow(x))


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