I've discovered a surprising behaviour by apply
that I wonder if anyone can explain. Lets take a simple matrix:
> (m = matrix(1:8,ncol=4))
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
We can flip it vertically thus:
> apply(m, MARGIN=2, rev)
[,1] [,2] [,3] [,4]
[1,] 2 4 6 8
[2,] 1 3 5 7
This applies the rev()
vector reversal function iteratively to each column. But when we try to apply rev by row we get:
> apply(m, MARGIN=1, rev)
[,1] [,2]
[1,] 7 8
[2,] 5 6
[3,] 3 4
[4,] 1 2
.. a 90 degree anti-clockwise rotation! Apply delivers the same result using FUN=function(v) {v[length(v):1]}
so it is definitely not rev's fault.
Any explanation for this?
The documentation states that
From that perspective, this behaviour is not a bug whatsoever, that's how it intended to work.
One may wonder why this is chosen to be a default setting, instead of preserving the structure of the original matrix. Consider the following example:
Consistent? Indeed, why would we expect anything else?
When you pass a row vector to rev, it returns a column vector.
which is not what you expected
So, you'll have to transpose the call to apply to get what you want
This is because
apply
returns a matrix that is defined column-wise, and you're iterating over the rows.The first application of
apply
presents each row, which is then a column in the result.Presenting the function
print
shows what's being passed torev
at each iteration:That is, each call to print is passed a vector. Two calls, and
c(1,3,5,7)
andc(2,4,6,8)
are being passed to the function.Reversing these gives
c(7,5,3,1)
andc(8,6,4,2)
, then these are used as the columns of the return matrix, giving the result that you see.