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?
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 .
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).
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
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