计算皮尔森相关系数的差异

时间:2013-10-05 13:28:23

标签: r correlation

在R中,计算皮尔逊相关系数似乎存在差异,(a)在一步中使用原始得分公式和(b)首先分别评估分子和分母。特别是,当我在一步中进行计算时,结果是错误的,但是当我首先分别评估分子和分母时它是正确的。怎么会?我可能做错了什么,但我无法弄清楚它是什么。

##data
x <- 1:5
y <- 5:1
##x squared, y squared, x times y; for raw score formula
xx <- x*x
yy <- y*y
xy <- x*y
##correlation coefficient; the value that should come out
cor(x,y) #-1
##raw score formula, in one line
wrong <- length(xy)*sum(xy)-sum(x)*sum(y)/
sqrt((length(xx)*sum(xx)-sum(x)^2)*(length(yy)*sum(yy)-sum(y)^2))
wrong #170.5
##raw score formula, separating numerator and denominator
numerator <- length(xy)*sum(xy)-sum(x)*sum(y)
denominator <- sqrt((length(x)*sum(xx)-sum(x)^2)*(length(y)*sum(yy)-sum(y)^2))
correct <- numerator/denominator
correct #-1

我在Xubuntu 12.04中使用R 2.14.1。

1 个答案:

答案 0 :(得分:4)

这是操作错误的顺序。

分子中还需要一组括号:

notwrong <- (length(xy)*sum(xy)-sum(x)*sum(y))/
  sqrt((length(xx)*sum(xx)-sum(x)^2)*(length(yy)*sum(yy)-sum(y)^2))
notwrong #-1