【问题标题】:discrepancy in calculating pearson correlation coefficient计算皮尔逊相关系数的差异
【发布时间】:2013-10-12 11:16:35
【问题描述】:

在 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。

【问题讨论】:

    标签: r correlation


    【解决方案1】:

    这是操作顺序错误。

    分子中还需要一组括号:

    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
    

    【讨论】:

    • 我一遍又一遍地查看我的公式,所以我很惊讶我错过了。非常感谢。
    猜你喜欢
    • 2012-11-18
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2011-09-10
    • 2020-05-23
    • 2018-07-23
    • 2016-03-04
    相关资源
    最近更新 更多