如何在R中從相關性檢驗中提取相關係數的值?


要在R中執行相關性檢驗,我們需要使用cor.test函式以及兩個變數,它會返回許多值,例如檢驗統計量值、自由度、p值、置信區間和相關係數的值。如果我們想從相關性檢驗輸出中提取相關係數的值,則可以使用estimate函式,如下面的示例所示。

示例

 即時演示

x1<-rnorm(20,5,2)
y1<-rnorm(20,5,1)
cor.test(x1,y1)

輸出

Pearson's product-moment correlation
data: x1 and y1
t = -0.13423, df = 18, p-value = 0.8947
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.4675990 0.4167308
sample estimates:
cor
-0.03162132

cor.test(x1,y1)$estimate cor -0.08194057

示例

 即時演示

x2<-runif(5000,2,5)
y2<-runif(5000,2,10)
cor.test(x2,y2)

輸出

Pearson's product-moment correlation
data: x2 and y2
t = -1.4823, df = 4998, p-value = 0.1383
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.048653479 0.006760764
sample estimates:
cor
-0.02096246

cor.test(x2,y2)$estimate cor 0.01301688

示例

 即時演示

x3<-runif(50,2,5)
y3<-runif(50,2,10)
cor.test(x3,y3)

輸出

Pearson's product-moment correlation
data: x3 and y3
t = -0.80709, df = 48, p-value = 0.4236
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.3817626 0.1680496
sample estimates:
cor
-0.1157106

cor.test(x3,y3)$estimate cor 0.1031475

示例

 即時演示

x4<-rexp(500,2.1)
y4<-rexp(500,5.75)
cor.test(y4,y4)

輸出

Pearson's product-moment correlation
data: y4 and y4
t = Inf, df = 498, p-value < 2.2e-16
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
1 1
sample estimates:
cor
1

cor.test(y4,y4)$estimate cor 1

示例

 即時演示

x5<-rpois(100000,2)
y5<-rpois(100000,5)
cor.test(y5,y5)

輸出

Pearson's product-moment correlation
data: y5 and y5
t = 1.5006e+10, df = 99998, p-value < 2.2e-16
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
1 1
sample estimates:
cor
1

cor.test(y5,y5)$estimate cor 1

更新於: 2020年10月10日

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.