I noticed that using apply() on a margin of an array produce an output where the dimensions are rearranged : the dimensions on which the operation was applied becomes the first dimension in the output.
This is an example of how apply() changes the ordering of dimensions for array of dim>2.
We take a 3-dim array and apply an addition on the second dimension
a <- array(1:24,dim=c(3,4,2));a
## , , 1
##
## [,1] [,2] [,3] [,4]
## [1,] 1 4 7 10
## [2,] 2 5 8 11
## [3,] 3 6 9 12
##
## , , 2
##
## [,1] [,2] [,3] [,4]
## [1,] 13 16 19 22
## [2,] 14 17 20 23
## [3,] 15 18 21 24
b <- apply(a,c(1,3),function(x) x+1);b
## , , 1
##
## [,1] [,2] [,3]
## [1,] 2 3 4
## [2,] 5 6 7
## [3,] 8 9 10
## [4,] 11 12 13
##
## , , 2
##
## [,1] [,2] [,3]
## [1,] 14 15 16
## [2,] 17 18 19
## [3,] 20 21 22
## [4,] 23 24 25
The second dimension is now the first one. Of course this change doesn’t occur when we apply an operation that collapse the dimension (mean,sum…), because the dimensions over which the operation is produced will disappear.
My questions are :
Why does apply behaves like that ? I am sure there is a reason, I would like to know it.
Is there a simple way to avoid it ? I have to admit my knowledge of the apply family is limited to apply, lapply, sapply. Maybe there is an easy way to apply a function on a margin of an array and producing an array with the same dimensions.
I identified two questions related to mine:
An unanswered question which is basically similar as mine, but more specific to the author's problem.
https://stackoverflow.com/questions/21815777/double-apply-loop-in-r-rearranging-dimensions-of-the-output
A similar question about plyr::aaply. I don't know this function so I am not able to say on wich extent this problem is related to apply.
how to use aaply and retain order of dimensions in array?