[R] division of col by the sum of the col

peter dalgaard pdalgd at gmail.com
Wed Sep 24 00:10:19 CEST 2014


On 23 Sep 2014, at 23:30 , Rolf Turner <r.turner at auckland.ac.nz> wrote:

> On 24/09/14 03:10, carol white wrote:
>> Hi, If I want to divide the column of a matrix by the sum of the
>> column, should I loop over the columns or can I use apply family?
> 
> m1 <- apply(m,2,function(x){x/sum(x)})
> 
> should do what you want IIUYC.

It might, but there's a surprise if you do the same thing with rows.

The canonical construction is

sweep(M, 2, apply(M, 2, sum), "/")

although efficiency suggests replacing the apply() with colSums(M) nowadays.

> 
> cheers,
> 
> Rolf Turner
> 
> -- 
> Rolf Turner
> Technical Editor ANZJS
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list