24

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?

markus
  • 25,843
  • 5
  • 39
  • 58
Museful
  • 6,711
  • 5
  • 42
  • 68

1 Answers1

35

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
Roland
  • 127,288
  • 10
  • 191
  • 288