Reputation: 131
Im trying to extract 95 percent confidence interval
from the result of pearson correlation.
My output looks like this:
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
I get it with the following code
t <- apply(FNR[, -1], 2, cor.test, FNR$HDL, method="pearson")
I would appreciate any help. Thanks.
Upvotes: 4
Views: 8078
Reputation: 263352
Let's look at the ?cor.test page and then modify the last example so it resembles your code:
t <- apply(USJudgeRatings[, -1], 2, cor.test, USJudgeRatings$CONT, method="pearson")
This is the first sublist of the returned value:
> 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"
To get all the conf.int
nodes from that list with 11 items, use sapply
with the "[["
function and given the character-valued name, "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
The sapply
function returns a column-oriented matrix result (at least with the default of simplify=TRUE) when given a set of arguments that return equal length values as is the case here.
Upvotes: 3
Reputation: 93811
cor.test
returns a list with various elements, including the confidence interval. You can see the structure of the object returned by cor.test
as follows (using the built-in mtcars
data frame for illustration):
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"
Now extract the confidence interval:
ct$conf.int[1:2]
[1] -0.9338264 -0.7440872
Upvotes: 6