0

在 R 中,计算 pearson 相关系数似乎存在差异,在 (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。

4

1 回答 1

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
于 2013-10-05T13:42:10.267 回答