Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum array along 3rd dimension

What is the canonical way to sum a 3D array along dimension 3 (thereby yielding a matrix)?

I know I can apply(A,c(1,2),sum) but (wrongly or rightly) I got the impression from somewhere that using apply is no better than using for loops.

I could probably aperm the array, colSum it, then unaperm it again, but that wouldn't be very readable.

Is there a better way?

like image 966
Museful Avatar asked May 02 '16 10:05

Museful


People also ask

How do I sum across a dimension in Matlab?

S = sum( A , dim ) returns the sum along dimension dim . For example, if A is a matrix, then sum(A,2) is a column vector containing the sum of each row. S = sum( A , vecdim ) sums the elements of A based on the dimensions specified in the vector vecdim .

How do I sum an array in R?

To find the sum of all array elements in R, we can use Reduce function with plus sign. For Example, if we have an array called ARRAY and we want to find the sum of all values in this array then we can use the command Reduce("+",ARRAY).


1 Answers

Use rowSums. It offers a dims parameter which specifies "[w]hich dimensions are regarded as ‘rows’ or ‘columns’ to sum over. For row*, the sum or mean is over dimensions dims+1".

a <- array(1:16, c(2, 2, 2))
#, , 1
#
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4
#
#, , 2
#
#     [,1] [,2]
#[1,]    5    7
#[2,]    6    8

rowSums(a, dims = 2)
#     [,1] [,2]
#[1,]    6   10
#[2,]    8   12
like image 160
Roland Avatar answered Sep 27 '22 00:09

Roland