Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an R function for the element-wise summation of the matrices stored as elements in single list object? [duplicate]

Tags:

r

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?

like image 456
FairyOnIce Avatar asked Jan 03 '13 21:01

FairyOnIce


2 Answers

See ?Reduce.

From the example:

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

Then you can

add(myList)
like image 153
GSee Avatar answered Sep 28 '22 05:09

GSee


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.

like image 44
Paul Hiemstra Avatar answered Sep 28 '22 06:09

Paul Hiemstra