Skip to content
Prev 248621 / 398502 Next

sapply puzzlement

On Jan 27, 2011, at 7:16 PM, Ernest Adrogu? i Calveras wrote:

            
Two methods:

A) use sweep  (which by default takes the difference)

 > sweep(z, 2, means)
           V1         V2
1  0.3333333 -2.7142857
2         NA  7.2857143
3 -0.6666667 -3.7142857
4 -6.6666667         NA
5         NA -0.7142857
6  1.3333333  1.2857143
7  3.3333333 -1.7142857
8  2.3333333  0.2857143


B) use the scale function (whose "whole purpose in life" is to  
subtract the mean and possibly divide by the standard deviation which  
we suppressed in this case with the scale=FALSE argument)

 > scale(z, scale=FALSE)
           V1         V2
1  0.3333333 -2.7142857
2         NA  7.2857143
3 -0.6666667 -3.7142857
4 -6.6666667         NA
5         NA -0.7142857
6  1.3333333  1.2857143
7  3.3333333 -1.7142857
8  2.3333333  0.2857143
attr(,"scaled:center")
        V1        V2
  9.666667 10.714286