[R] Multiple Vector with matrix in R

arun smartpink111 at yahoo.com
Fri Nov 16 22:17:53 CET 2012


HI,

set.seed(15)
mat1<-matrix(sample(1:1000000,8000000,replace=TRUE),nrow=8000)
w <- 1/1:8000
system.time(diag(w)%*%mat1) 
#   user  system elapsed 
# 54.235   0.444  54.792 
system.time(sweep(mat1,MARGIN=1,w,`*`) ) 
#   user  system elapsed 
#  0.220   0.044   0.265 
system.time(t(sapply(seq_along(w),function(i) mat1[i,]*w[i])))
 #  user  system elapsed 
 # 0.288   0.048   0.337 
system.time(sapply(seq_along(w),function(i) mat1[i,]*w[i])) #without the transpose, Rui's method is better
 #  user  system elapsed 
 # 0.180   0.028   0.207 
system.time(do.call(rbind,lapply(seq_along(w),function(i) mat1[i,]*w[i])))
#   user  system elapsed 
#  0.228   0.024   0.250 
system.time(lapply(seq_along(w),function(i) mat1[i,]*w[i]))
#   user  system elapsed 
#  0.140   0.000   0.139 

A.K.




----- Original Message -----
From: Rui Barradas <ruipbarradas at sapo.pt>
To: frespider <frespider at hotmail.com>
Cc: r-help at r-project.org
Sent: Friday, November 16, 2012 2:45 PM
Subject: Re: [R] Multiple Vector with  matrix in R

Hello,

Try the following.

t(sapply(seq_along(w), function(i) mat1[i,]*w[i]))

Hope this helps,

Rui Barradas
Em 16-11-2012 16:34, frespider escreveu:
> Hi
>
> Can someone show me an easy way to multiple a weighted vector with an
> matrix?
>
> example below
> mat1<-matrix(sample(1:100,80,replace=TRUE),ncol=8)
> w <- 1/1:10
>
> I want the first element in w to be multiplied by the first row of mat1 and
> 2nd element in w to be multiplied with the 2nd row and so on.
>
> I have huge matrix is there an easy way other than diag(w)%*%mat1
>
> Thanks
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Multiple-Vector-with-matrix-in-R-tp4649764.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.

______________________________________________
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