title: Cumulative multidimensional array sum in R
body: <p>In R, how do you generalize the calculation of cumulative sum over different margins of a matrix to a multidimensional array?</p>
  
  <p>For example, given the matrix</p>
  
  <pre><code>a2 &lt;- array(1:6, dim = c(2,3))
  </code></pre>
  
  <blockquote>
  <pre><code>     [,1] [,2] [,3]
  [1,]    1    3    5
  [2,]    2    4    6
  </code></pre>
  </blockquote>
  
  <p>The cumulative sum over the different margins can be calculated using <code>apply</code>:</p>
  
  <pre><code>apply(a2, 2, cumsum)
  </code></pre>
  
  <blockquote>
  <pre><code>     [,1] [,2] [,3]
  [1,]    1    3    5
  [2,]    3    7   11
  </code></pre>
  </blockquote>
  
  <pre><code>t(apply(a2, 1, cumsum))
  </code></pre>
  
  <blockquote>
  <pre><code>     [,1] [,2] [,3]
  [1,]    1    4    9
  [2,]    2    6   12
  </code></pre>
  </blockquote>
  
  <p>Note that some reshaping is required in the latter case. Now the question is:</p>
  
  <p>How would you calculate cumulative sums for a multidimensional array?</p>
  
  <p>E.g., for a three dimensional array like:</p>
  
  <pre><code>a3 &lt;- array(1:24, dim = c(2,3,4))
  </code></pre>
  
  <p>I am interested in the cumulative sum over the rows, cols, and the third dimension, preserving the structure of the original array. Specifically, the row cumulative sum should be:</p>
  
  <blockquote>
  <pre><code>, , 1
  
       [,1] [,2] [,3]
  [1,]    1    4    9
  [2,]    2    6   12
  
  , , 2
  
       [,1] [,2] [,3]
  [1,]    7   16   27
  [2,]    8   18   30
  
  , , 3
  
       [,1] [,2] [,3]
  [1,]   13   28   45
  [2,]   14   30   48
  
  , , 4
  
       [,1] [,2] [,3]
  [1,]   19   40   63
  [2,]   20   42   66
  </code></pre>
  </blockquote>
  
  <p>What would be the answer for an n-dimensional array? </p>