Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to multiply list elements by a vector?

Tags:

list

r

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

like image 668
N.Varela Avatar asked Dec 14 '22 09:12

N.Varela


1 Answers

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
like image 167
Badger Avatar answered Jan 06 '23 17:01

Badger