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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With