[R] Multiplying a list of matrices with a vector

David Winsemius dwinsemius at comcast.net
Thu Sep 29 15:09:54 CEST 2011


On Sep 28, 2011, at 6:26 PM, R. Michael Weylandt wrote:

> Untested:
>
> mapply('*', LL, vec)
>
> Those should be backticks but I can't type them on my phone

Actually mapply does not require backticks since it is expecting its  
functions to be quoted anyway, but it didn't seem to work as you (and  
I) expected.

 > mapply('*', LL, vec)
       [,1] [,2] [,3]
  [1,]    1    2    3
  [2,]    0    0    0
  [3,]    0    0    0
  [4,]    0    0    0
  [5,]    1    2    3
  [6,]    0    0    0
  [7,]    0    0    0
  [8,]    0    0    0
  [9,]    1    2    3

What is needed is to add SIMPLIFY=FALSE

 > mapply('*', LL, vec, SIMPLIFY=FALSE)
$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

-- 
David.


>
> 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.
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list