R:如何从cor.test函数中提取置信区间

时间:2016-07-01 16:33:46

标签: r correlation confidence-interval

我试图从皮尔森相关结果中提取95 percent confidence interval

我的输出如下:

Pearson's product-moment correlation

data:  newX[, i] and newY
t = 2.1253, df = 6810, p-value = 0.0336
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 0.001998576 0.049462864
sample estimates:
       cor 
0.02574523 

我使用以下代码

t <- apply(FNR[, -1], 2, cor.test, FNR$HDL, method="pearson")

我将不胜感激任何帮助。感谢。

2 个答案:

答案 0 :(得分:4)

cor.test返回包含各种元素的列表,包括置信区间。您可以按如下方式查看cor.test返回的对象的结构(使用内置的mtcars数据框进行说明):

ct = cor.test(mtcars$mpg, mtcars$wt, method="pearson")

str(ct)
List of 9
 $ statistic  : Named num -9.56
  ..- attr(*, "names")= chr "t"
 $ parameter  : Named int 30
  ..- attr(*, "names")= chr "df"
 $ p.value    : num 1.29e-10
 $ estimate   : Named num -0.868
  ..- attr(*, "names")= chr "cor"
 $ null.value : Named num 0
  ..- attr(*, "names")= chr "correlation"
 $ alternative: chr "two.sided"
 $ method     : chr "Pearson's product-moment correlation"
 $ data.name  : chr "mtcars$mpg and mtcars$wt"
 $ conf.int   : atomic [1:2] -0.934 -0.744
  ..- attr(*, "conf.level")= num 0.95
 - attr(*, "class")= chr "htest"

现在提取置信区间:

ct$conf.int[1:2]   
  

[1] -0.9338264 -0.7440872

答案 1 :(得分:3)

让我们看看?cor.test页面,然后修改最后一个示例,使其类似于您的代码:

t <- apply(USJudgeRatings[, -1], 2, cor.test, USJudgeRatings$CONT, method="pearson")

这是返回值的第一个子列表:

> str(t[1])
List of 1
 $ INTG:List of 9
  ..$ statistic  : Named num -0.861
  .. ..- attr(*, "names")= chr "t"
  ..$ parameter  : Named int 41
  .. ..- attr(*, "names")= chr "df"
  ..$ p.value    : num 0.395
  ..$ estimate   : Named num -0.133
  .. ..- attr(*, "names")= chr "cor"
  ..$ null.value : Named num 0
  .. ..- attr(*, "names")= chr "correlation"
  ..$ alternative: chr "two.sided"
  ..$ method     : chr "Pearson's product-moment correlation"
  ..$ data.name  : chr "newX[, i] and USJudgeRatings$CONT"
  ..$ conf.int   : atomic [1:2] -0.417 0.174
  .. ..- attr(*, "conf.level")= num 0.95
  ..- attr(*, "class")= chr "htest"

要从该列表中获取包含11个项目的所有conf.int个节点,请使用带有sapply函数的"[["并指定字符值名称,&#34; conf.int&# 34;:

> sapply(t, "[[", "conf.int")
           INTG       DMNR       DILG       CFMG       DECI       PREP
[1,] -0.4168591 -0.4339992 -0.2890276 -0.1704402 -0.2195110 -0.2898732
[2,]  0.1741182  0.1537524  0.3115762  0.4199860  0.3770813  0.3107427
           FAMI       ORAL       WRIT       PHYS       RTEN
[1,] -0.3234896 -0.3112193 -0.3396845 -0.2501717 -0.3306462
[2,]  0.2768389  0.2893898  0.2599541  0.3489073  0.2694228

当给定一组返回相等长度值的参数时,sapply函数返回面向列的矩阵结果(至少默认值为simplify = TRUE)。