如何在 R 中執行 Spearman 相關性檢驗時避免“無法計算帶有重複值的精確 p 值”的警告?


當變數不是連續的,但可以進行排序時,我們不使用皮爾遜相關係數來查詢線性關係,在這種情況下,斯皮爾曼相關係數就會派上用場。由於斯皮爾曼相關係數考慮了值的秩,因此相關性檢驗會忽略相同的秩以查詢 p 值,從而導致“無法計算帶有重複值的精確 p 值”的警告。這可以透過在 cor.test 函式內部使用 exact = FALSE 來避免。

示例

考慮以下向量並執行斯皮爾曼相關性檢驗以檢查它們之間的關係:

 線上演示

x1<-rpois(20,2)
y1<-rpois(20,5)
cor.test(x1,y1,method="spearman")

輸出

   Spearman's rank correlation rho
data: x1 and y1
S = 1401.7, p-value = 0.8214
alternative hypothesis: true rho is not equal to 0
sample estimates:
   rho
-0.05390585
Warning message:
In cor.test.default(x1, y1, method = "spearman") :
Cannot compute exact p-value with ties

這裡,我們得到了關於重複值的警告,這可以透過使用 exact=FALSE 來避免,如下所示:

示例

cor.test(x1,y1,method="spearman",exact=FALSE)

輸出

   Spearman's rank correlation rho
data: x1 and y1
S = 1401.7, p-value = 0.8214
alternative hypothesis: true rho is not equal to 0
sample estimates:
   rho
-0.05390585

讓我們再看一些例子:

示例

 線上演示

x2<-sample(1:100,500,replace=TRUE)
y2<-sample(1:50,500,replace=TRUE)
cor.test(x2,y2,method="spearman")

輸出

   Spearman's rank correlation rho
data: x2 and y2
S = 20110148, p-value = 0.4387
alternative hypothesis: true rho is not equal to 0
sample estimates:
   rho
0.03470902
Warning message:
In cor.test.default(x2, y2, method = "spearman") :
Cannot compute exact p-value with ties

示例

cor.test(x2,y2,method="spearman",exact=FALSE)

輸出

   Spearman's rank correlation rho
data: x2 and y2
S = 20110148, p-value = 0.4387
alternative hypothesis: true rho is not equal to 0
sample estimates:
   rho
0.03470902

示例

 線上演示

x3<-sample(101:110,5000,replace=TRUE)
y3<-sample(501:510,5000,replace=TRUE)
cor.test(x3,y3,method="spearman")

輸出

   Spearman's rank correlation rho
data: x3 and y3
S = 2.0642e+10, p-value = 0.5155
alternative hypothesis: true rho is not equal to 0
sample estimates:
   rho
0.009199129
Warning message:
In cor.test.default(x3, y3, method = "spearman") :
Cannot compute exact p-value with ties

示例

cor.test(x3,y3,method="spearman",exact=FALSE)

輸出

   Spearman's rank correlation rho
data: x3 and y3
S = 2.0642e+10, p-value = 0.5155
alternative hypothesis: true rho is not equal to 0
sample estimates:
   rho
0.009199129

更新於: 2020年9月8日

19K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告