[R] Multiplying a list of matrices with a vector
R. Michael Weylandt <michael.weylandt@gmail.com>
michael.weylandt at gmail.com
Thu Sep 29 00:26:46 CEST 2011
Untested:
mapply('*', LL, vec)
Those should be backticks but I can't type them on my phone
Michael
On Sep 28, 2011, at 6:04 PM, "Mendolia, Franco" <fmendolia at mcw.edu> wrote:
> Hi all!
>
> I have a list of matrices and I want to multiply the ith element of the list with the ith element of a another vector. That is,
>
>> LL <- list(A=diag(3),B=diag(3),C=diag(3))
>> vec <- 1:3
>> for(i in 1:3)
> + {
> + LL[[i]] <- LL[[i]]*vec[i]
> + }
>> LL
> $A
> [,1] [,2] [,3]
> [1,] 1 0 0
> [2,] 0 1 0
> [3,] 0 0 1
>
> $B
> [,1] [,2] [,3]
> [1,] 2 0 0
> [2,] 0 2 0
> [3,] 0 0 2
>
> $C
> [,1] [,2] [,3]
> [1,] 3 0 0
> [2,] 0 3 0
> [3,] 0 0 3
>
> Is there another (more efficient) way of doing this without using loops? I found an older entry in this list with a similar problem, where the list elements were always multiplied with the same number, e.g., lapply(LL, function(x) x*3) and I was looking for something similar.
>
> Best,
> Franco
> ______________________________________________
> 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