Let's use a better example to see what happens:
m = matrix(c(1,2,7,10,12,18),nrow=2)
# [,1] [,2] [,3]
#[1,] 1 7 12
#[2,] 2 10 18
apply(m, 1, scale)
# [,1] [,2]
#[1,] -1.02888681 -1
#[2,] 0.06052275 0
#[3,] 0.96836405 1
As you see scale
is applied to the matrix rows and the resulting vectors combined as columns of the result matrix.
apply(m, 2, scale)
# [,1] [,2] [,3]
#[1,] -0.7071068 -0.7071068 -0.7071068
#[2,] 0.7071068 0.7071068 0.7071068
Now scale
is applied to the matrix columns, but the resulting vectors are again combined as columns of the result matrix. And indeed this is documented in help("apply")
:
If each call to FUN returns a vector of length n, then apply returns an array of dimension c(n, dim(X)[MARGIN]) if n > 1.
Edit:
You can avoid the problem if you do something like this:
(m-apply(m,1,mean))/apply(m,1,sd)
[,1] [,2] [,3]
[1,] -1.028887 0.06052275 0.9683641
[2,] -1.000000 0.00000000 1.0000000