Possible Duplicate:
Sum a list of matrices
Add together a list of matrices element-by-element
I have a R list object. Each element of the list contains 3 by 3 matrix. I want to sum all the matrices element-wise. That is:
myList <- list();
myList[[1]] <- matrix(1:9,3,3)
myList[[2]] <- matrix((1:9)*10,3,3)
Then I want the final output output
myList[[1]]+myList[[2]]
[,1] [,2] [,3]
[1,] 11 44 77
[2,] 22 55 88
[3,] 33 66 99
Of course I can write a loop for this calculation but loop in R is very slow. Is there built in function in R which does this business?
See ?Reduce
.
From the example:
## A general-purpose adder:
add <- function(x) Reduce("+", x)
Then you can
add(myList)
Alternatively, you could put the data in a multi-dimensional array instead of a list, and use apply
on that.
require(abind)
m = abind(matrix(1:9,3,3), matrix((1:9)*10,3,3), along = 3)
yields a three dimensional array. Then use apply
:
apply(m, 1:2, sum)
Disclaimer: I did not test this code as I do not have R available right now. However, I do wanted you to be aware of this option.
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