计算R中的平方偏差之和

Joh*_*hnK 8 statistics r

如何计算向量的平方偏差(从平均值)的总和?

我尝试使用该命令

总和(X-平均值(X))^ 2

但不幸的是,这返回的是-1.998401e-15,这是不对的.是否有一个微妙的操作符,如括号,我可能在这里失踪?

谢谢.

Dir*_*tel 15

这可能是正确的.-2.0到10 ^ 15的幂意味着它基本上为零.但正如贾斯汀在评论中所指出的,你有

    (sum (x - mean(x) )^2
Run Code Online (Sandbox Code Playgroud)

当你可能意味着:

    sum( (x - mean(x) )^2 )
Run Code Online (Sandbox Code Playgroud)

  • @JohnK:继续阅读R [FAQ 7.31](http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f )... (2认同)

Sve*_*ein 10

您还可以使用其他方法计算偏差平方和:

x <- 1:10 #an example vector

# the 'classic' approach
sum( (x - mean(x) )^2 )
# [1] 82.5

# based on the variance
var(x) * (length(x) - 1)
#[1] 82.5
Run Code Online (Sandbox Code Playgroud)

后者的作用是因为var(x) = (x - mean(x))^2) / (length(x) - 1).这是样本差异:

在此输入图像描述