title: R: Apply to slices of an array and return an array
body: <p>I want to find the simplest way to apply a function across slices of an array, where each application of the function returns a matrix, and receive a sensible array object as the final answer.</p>
  
  <p>I feel like there should be a simple way to do this with apply function, but I feel like I need a <code>simplify = 'array'</code> option, which would be super convenient. The closest I get is this:</p>
  
  <pre><code>dims = c(2,3,10,4,5)
  arr = array(runif(prod(dims)),dim = dims, dimnames = 
            list(
              paste0('a',1:dims[1]),
              paste0('b',1:dims[2]),
              paste0('c',1:dims[3]),
              paste0('d',1:dims[4]),
              paste0('e',1:dims[5])
            ))
  
  result = apply(arr, c(4,5), function(x) apply(x, c(3), function(y) (y - y[,1])^2 ) )
  </code></pre>
  
  <p>The <code>result</code> should be an array with dimension <code>c(2,3,10,4,5)</code> or some permutation thereof.</p>
  
  <p>I could get to the right form by calling <code>as.array</code> on <code>result</code> with the appropriate dimensions, but there should be an easier way that preserves the <code>dimnames</code> automatically.</p>