[R] matrix column division by vector

Bert Gunter gunter.berton at gene.com
Wed May 14 17:17:35 CEST 2014


Oh my goodness David! Don't forget that matrices are just vectors in
column major order.


> m/rep(v,e=2)
     [,1] [,2] [,3]
[1,]    2    2    2
[2,]    1    1    1

(the generalization is obvious)

should be far more efficient and simpler  than running apply loops.

-- Cheers,
Bert

Bert Gunter
Genentech Nonclinical Biostatistics
(650) 467-7374

"Data is not information. Information is not knowledge. And knowledge
is certainly not wisdom."
H. Gilbert Welch




On Wed, May 14, 2014 at 7:59 AM, David L Carlson <dcarlson at tamu.edu> wrote:
> You don't need do.call:
>
>> t(t(m)/v)
>      [,1] [,2] [,3]
> [1,]    2    2    2
> [2,]    1    1    1
>
>> t(apply(m, 1, function(x) x/v))
>      [,1] [,2] [,3]
> [1,]    2    2    2
> [2,]    1    1    1
>
> -------------------------------------
> David L Carlson
> Department of Anthropology
> Texas A&M University
> College Station, TX 77840-4352
>
>
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of carol white
> Sent: Wednesday, May 14, 2014 9:52 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] matrix column division by vector
>
> Hi,
> What is the elegant script to divide the columns of a matrix by the respective position of a vector elements?
>
> m=rbind(c(6,4,2),c(3,2,1))
>
> v= c(3,2,1)
>
> res= 6/3   4/2  2/1
>         3/3   2/2    1/1
>
>
> this is correct
> mat2 = NULL
>
> for (i in 1: ncol(m))
>
>     mat2 = cbind(mat2, m[,i]/ v[i])
>
>
> but how to do more compact and elegant with for ex do.call?
>
> Many thanks
>
> Carol
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.



More information about the R-help mailing list