31

Is it possible to find the p-value in pearson correlation in R?

To find the pearson correlation, I usually do this

col1 = c(1,2,3,4)
col2 = c(1,4,3,5)
cor(col1,col2)
# [1] 0.8315218

But how I can find the p-value of this?

MichaelChirico
  • 1,270
  • 1
  • 9
  • 20
tubby
  • 593
  • 2
  • 6
  • 9

3 Answers3

43

you can use cor.test :

col1 = c(1,2,3,4) 
col2 = c(1,4,3,5)
cor.test(col1,col2) 

which gives :

# Pearson's product-moment correlation   
# data:  col1 and col2   
# t = 2.117, df = 2, p-value = 0.1685   
# alternative hypothesis: true correlation is not equal to 0   
# 95 percent confidence interval:   
#  -0.6451325  0.9963561   
# sample estimates:   
#       cor    
# 0.8315218    

More information about the statistics and extra parameters at the official page:

https://stat.ethz.ch/R-manual/R-patched/library/stats/html/cor.test.html

MichaelChirico
  • 1,270
  • 1
  • 9
  • 20
brumar
  • 2,092
  • 11
  • 14
10

If you want only the P value:

> cor.test(col1,col2)$p.value
[1] 0.1684782
rnso
  • 8,893
  • 14
  • 50
  • 94
7

The following will do as you ask:

 library(Hmisc) # You need to download it first.
 rcorr(x, type="pearson") # type can be pearson or spearman

Here x is a data frame, and rcorr returns every correlation which it is possible to form from the "x" data frame.

Or you could calculate the statistic yourself:

$$ t = \frac{\hat{\rho}}{\sqrt{\frac{1-\hat{\rho}^2}{n-2}}} $$

Where $\hat{\rho}$ is the pearson correlation estimated from the data, and n is the sample size.

Repmat
  • 3,182
  • 1
  • 15
  • 32
  • Thanks, but what is x ? I think it's some concatenation of col1 and col2 because we need two vectors to calculate pearson correlation. But can you tell me what x is? – tubby May 25 '15 at 21:49
  • It is a data frame, see my update. – Repmat May 25 '15 at 21:51