简体   繁体   English

如何沿第 3 维求和数组

[英]How to sum array along 3rd dimension

What is the canonical way to sum a 3D array along dimension 3 (thereby yielding a matrix)?沿第 3 维对 3D 数组求和(从而产生矩阵)的规范方法是什么?

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.我知道我可以apply(A,c(1,2),sum)但是(错误或正确)我从某个地方得到的印象是使用apply并不比使用for循环更好。

I could probably aperm the array, colSum it, then un aperm it again, but that wouldn't be very readable.我可能可以aperm数组, colSum它,然后再次 un aperm它,但这不会很可读。

Is there a better way?有更好的方法吗?

Use rowSums .使用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".它提供了一个dims参数,该参数指定“[w] 个维度被视为要求和的‘行’或‘列’。对于行 *,总和或均值超过维度 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM