34
votes
$\begingroup$

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?

$\endgroup$
1
  • 3
    $\begingroup$ The help on cor (?cor) explicitly mentions cor.test (under "See Also") $\endgroup$
    – Glen_b
    May 26, 2015 at 3:37

3 Answers 3

47
votes
$\begingroup$

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

$\endgroup$
1
  • $\begingroup$ thanks, not enough points to upvote, used it though $\endgroup$
    – tubby
    May 25, 2015 at 23:08
10
votes
$\begingroup$

If you want only the P value:

> cor.test(col1,col2)$p.value
[1] 0.1684782
$\endgroup$
1
  • $\begingroup$ However, isn't cor.test a paired correlation test, different from cor (an independent samples correlation test)? $\endgroup$ May 24, 2021 at 6:10
8
votes
$\begingroup$

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.

$\endgroup$
2
  • $\begingroup$ 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? $\endgroup$
    – tubby
    May 25, 2015 at 21:49
  • $\begingroup$ It is a data frame, see my update. $\endgroup$
    – Repmat
    May 25, 2015 at 21:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.