Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a single value out of any statistics tests (e.g. value of spearman rho out of cor.test)

Tags:

r

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?

like image 669
Rivo Avatar asked Jul 10 '11 05:07

Rivo


2 Answers

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.

like image 131
James Avatar answered Sep 21 '22 13:09

James


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
like image 25
Mark Avatar answered Sep 18 '22 13:09

Mark