Statistics test in R outputs many descriptions. While they are useful, how can we just output or extract single values?
> cor.test(x,y,method="spearman", exact=F)
Spearman's rank correlation rho
data: x and y
S = 12767993, p-value = 0.0001517
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
-0.188074
particularly, what to do to just get out these values 0.0001517 and -0.188074 so I can store them for further analyses?
You can use $
subsetting of the test object. The relevant names are p.value
and estimate
.
> tst<-cor.test(1:10,rnorm(10),method="spearman")
> tst
Spearman's rank correlation rho
data: 1:10 and rnorm(10)
S = 140, p-value = 0.6818
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
0.1515152
.
> tst$p.value
[1] 0.6818076
> tst$estimate
rho
0.1515152
Edit
The other answers point out that you can investigate the structure of the object with str
to find the names to use with $
subsetting. You can also find out the names with names
:
> names(tst)
[1] "statistic" "parameter" "p.value" "estimate" "null.value"
[6] "alternative" "method" "data.name"
Another thing to consider is that you are looking at the printed version of the object, and the print method may be performing some calculations (it isn't in this case). You can check the object class with class(tst)
which reveals it is of class htest
. print.htest
is the relevant print method, but this is non-visible, so use getAnywhere(print.htest)
to view it.
test.res <- cor.test(x,y,method="spearman", exact=F)
Use str(test.res) to see the structure of your object
> str(test.res)
List of 8
$ statistic : Named num 182
..- attr(*, "names")= chr "S"
$ parameter : NULL
$ p.value : num 0.785
$ estimate : Named num -0.103
..- attr(*, "names")= chr "rho"
$ null.value : Named num 0
..- attr(*, "names")= chr "rho"
$ alternative: chr "two.sided"
$ method : chr "Spearman's rank correlation rho"
$ data.name : chr "1:10 and rnorm(10)"
- attr(*, "class")= chr "htest"
Any of these is available by using $ notation. If you are looking for getting the p.value use the following:
test.res$p.value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With