简体   繁体   English

R中尺度函数的统计公式

[英]statistical formula for scale function in R

what is mathematical formula of scale in R? R中比例的数学公式是什么? I just tried the following but it is not the same as scale(X) 我只是尝试了以下内容,但它与scale(X)不同

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

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

1) For each column subtract its mean and then divide by its standard deviation: 1)对于每一列,减去其平均值,然后除以其标准偏差:

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. 2)编写此代码的另一种方法非常接近问题中的代码,如下所示。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM