![](/img/trans.png)
[英]R: Calculating Pearson correlation coefficient in each cell along time line
[英]discrepancy in calculating pearson correlation coefficient
在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。
這是一個操作順序錯誤。
您需要在分子中再加上一組括號:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.