I know in R if I have a list of matrices, I can use the Reduce function to apply an operation across all the matrices. For example:
l <- list(matrix(rnorm(16), 4, 4), matrix(rnorm(16), 4, 4))
Reduce(`*`, l)
But what if I want to apply this operation across multiple lists? I could do a brute-force approach with a for loop but I feel like there should be a better way. I can do two lists with mapply
l2 <- l
mapply(`*`, l, l2, SIMPLIFY = FALSE)
But if I have more that two I'm not sure how to solve that.
The following thoughts all result in errors:
l3 <- l2
mapply(`*`, l, l2, l3, SIMPLIFY = FALSE)
Error in .Primitive("*")(dots[[1L]][[1L]], dots[[2L]][[1L]], dots[[3L]][[1L]]) :
operator needs one or two arguments
Reduce(`*`, list(l, l2, l3))
Error in f(init, x[[i]]) : non-numeric argument to binary operator
The desired output is a list of length 2 with the elementwise products of each matrix within each list. The brute-force loop would look like this:
out <- vector("list", length = 2)
for(i in 1:2){
out[[i]] <- l[[i]] * l2[[i]] * l3[[i]]
}