statistical formula for scale function in R

拥有回忆 提交于 2019-12-11 16:21:29

问题


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)


来源:https://stackoverflow.com/questions/57432184/statistical-formula-for-scale-function-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!