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.
I feel like there should be a simple way to do this with apply function, but I feel like I need a simplify = 'array' option, which would be super convenient. The closest I get is this:
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 ) )
The result should be an array with dimension c(2,3,10,4,5) or some permutation thereof.
I could get to the right form by calling as.array on result with the appropriate dimensions, but there should be an easier way that preserves the dimnames automatically.
apply, specify the margins you want to keep:apply(arr, 2:5, function(x){mean(x^2)})apply(arr^2, 2:5, mean)would even work in this particular case.