5

I want to multiply a list of matrices (with one row), like this:

lst <- list("111.2012"=matrix(c(1, 0, 6, NA, 1, 0),
                            nrow = 1, byrow = T),
          "112.2012"=matrix(c(6, 2, 2, 0, 3, NA),
                            nrow = 1, byrow = T))

with a vector like this (with the same length as each matrix):

vec <- c(1,2,3,1,2,3)

And expect this result:

$`111.2012`
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    0   18   NA    2    0

$`112.2012`
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    6    4    6    0    6   NA

I tried so far this:

mapply("*", lst, vec) 
Map("*", lst, vec)

Which gives my three times more numbers and the wrong ones. I also thought of using lapply within mapply to adress the list, but didn't know how to do it. Any suggestions? Thanks

N.Varela
  • 910
  • 1
  • 11
  • 25

2 Answers2

10

I believe you are looking for lapply(), since you are using a list lapply( lst, FUN= function(x) x*vec)

For more information see this.

Hope that helps!

lapply(lst,FUN= function(x) x*vec) ## My old clunky way

lapply(lst, "*" , vec) ## As informed by Richard Scriven (Thanks!)

$`111.2012`
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    0   18   NA    2    0

$`112.2012`
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    6    4    6    0    6   NA
Community
  • 1
  • 1
Badger
  • 1,043
  • 10
  • 25
4

The Map/mapply works by applying the function to corresponding elements of the input variabless. For a list of length 2, we have 2 elements i.e. lst[[1]] and lst[[2]] and for a vector of length 6, it will be 6. So, this creates an inequality. In order to rectify this, we place the vector in a list (by wrapping with list), so that it gets recycled to the length of the 'lst' and will be used as a whole for each element in the 'lst'.

Map("*", lst, list(vec))
#$`111.2012`
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    1    0   18   NA    2    0

#$`112.2012`
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    6    4    6    0    6   NA
akrun
  • 874,273
  • 37
  • 540
  • 662