Is there an R-function for elementary summation of matrices stored as elements in a single list object?

Possible duplicate:
Make a list of matrices
Match list of items by item

I have a list object R. Each list item contains a 3 by 3 matrix. I want to sum all matrices by items. I.e:

myList <- list(); myList[[1]] <- matrix(1:9,3,3) myList[[2]] <- matrix((1:9)*10,3,3) 

Then i need 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 the loop in R is very slow. Is there a built-in function in R that makes this business?

+8
r
source share
4 answers

See ?Reduce .

From an example:

 ## A general-purpose adder: add <- function(x) Reduce("+", x) 

Then you can

 add(myList) 
+14
source share

Alternatively, you can put data in a multidimensional array instead of a list and use apply to do this.

 require(abind) m = abind(matrix(1:9,3,3), matrix((1:9)*10,3,3), along = 3) 

gives a three-dimensional array. Then use apply :

 apply(m, 1:2, sum) 

Disclaimer: I have not tested this code since I don’t have R. However, I want you to know about it.

+4
source share

For those who wish:

 ffoo<-function(jloop){ barlist<-matrix(nr=25,nc=40) for (jj in 1:jloop) barlist<-barlist+foolist[[jj]] } baradd <- function(x) Reduce("+", x) 

Leads to:

 Rgames> foo<-matrix(1:1000,25) Rgames> for (jj in 1:5e5) foolist[[jj]]<-foo Rgames> system.time(baradd(foolist)) user system elapsed 1.7 0.0 1.7 Rgames> system.time(ffoo(1e5)) user system elapsed 0.3 0.0 0.3 
+3
source share
 > do.call("+", myList) [,1] [,2] [,3] [1,] 11 44 77 [2,] 22 55 88 [3,] 33 66 99 

But he fails for more than two, which is why I supported GSee's answer.

+2
source share

All Articles