首页 文章

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

提问于
浏览
0

在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 回答

  • 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
    

相关问题