R:如何从核心测试函数中提取置信区间



我试图从pearson相关性的结果中提取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")

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

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

让我们看一下?测试页面,然后修改最后一个示例,使其与您的代码相似:

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"[["函数并给定字符值名称"conf.int":

> 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),就像这里的情况。

最新更新