[R] A factor times a matrix

arun smartpink111 at yahoo.com
Tue Sep 17 15:38:55 CEST 2013



?sweep() would be a bit slower compared to other two methods.


b1<-do.call(rbind,replicate(1e6,b,simplify=FALSE))
 system.time(res1<- t(a*t(b1)))
#   user  system elapsed 
#  0.044   0.000   0.044 
 system.time(res2<- sweep(b1,2,a,"*"))
#   user  system elapsed 
#   0.14    0.00    0.14 
 system.time(res3<- b1%*% diag(a))
#   user  system elapsed 
#  0.084   0.000   0.083 
 identical(res1,res2)
#[1] TRUE
 all.equal(res1,res3)
#[1] TRUE
A.K.


________________________________
From: Pascal Oettli <kridox at ymail.com>
To: Edouard Hardy <hardy.edouard at gmail.com> 
Cc: R help <r-help at r-project.org>; arun <smartpink111 at yahoo.com> 
Sent: Monday, September 16, 2013 11:38 PM
Subject: Re: [R] A factor times a matrix



Hello,

To complete Arun's response, you also have:

> sweep(b,2,a,'*')
     [,1] [,2]
[1,]    1    8
[2,]    2   10
[3,]    3   12

or

> b %*% diag(a)
     [,1] [,2]
[1,]    1    8
[2,]    2   10
[3,]    3   12

Regards,
Pascal


2013/9/17 arun <smartpink111 at yahoo.com>

Hi,
> t(a*t(b))
>#     [,1] [,2]
>#[1,]    1    8
>#[2,]    2   10
>#[3,]    3   12
>
>A.K.
>
>
>Hello eveybody,
>
>I have a vector a and a matrix b :
>> a
>[1] 1 2
>> b
>[,1] [,2]
>[1,] 1 4
>[2,] 2 5
>[3,] 3 6
>
>With simple multiplication I get :
>> a * b
>[,1] [,2]
>[1,] 1 8
>[2,] 4 5
>[3,] 3 12
>
>I would like to have that :
>[,1] [,2]
>[1,] 1 8
>[2,] 2 10
>[3,] 3 12
>
>Fo now I use replicate bu I would like to do this in a simple way.
>
>Do you have a solution ?
>
>Thank you in advance
>
>______________________________________________
>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.
>


-- 

Pascal Oettli
Project Scientist
JAMSTEC

Yokohama, Japan



More information about the R-help mailing list