statistical formula for scale function in R

2019-08-20 07:05发布

问题:

what is mathematical formula of scale in R? I just tried the following but it is not the same as scale(X)

 ( X-colmeans(X))/ sapply(X, sd) 

回答1:

Since vector subtraction from matrices/data-frames works column-wise instead of row-wise, you have to transpose the matrix/data-frame before subtraction and then transpose back at the end. The result is the same as scale except for rounding errors. This is obviously a hassle to do, which I guess is why there's a convenience function.

x <- as.data.frame(matrix(sample(100), 10 , 10))
s <- scale(x)
my_s <- t((t(x) - colMeans(x))/sapply(x, sd))

all(s - my_s < 1e-15)
# [1] TRUE


回答2:

1) For each column subtract its mean and then divide by its standard deviation:

apply(X, 2, function(x) (x - mean(x)) / sd(x))

2) Another way to write this which is fairly close to the code in the question is the following. The main difference between this and the question is that the question's code recycles by column (which is not correct in this case) whereas the following code recycles by row.

nr <- nrow(X)
nc <- ncol(X)
(X - matrix(colMeans(X), nr, nc, byrow = TRUE)) / 
  matrix(apply(X, 2, sd), nr, nc, byrow = TRUE)