# Significance test for Pearson Correlation Coefficient

How can I compute the significance test (P value) for the correlation coefficient (r) using R or Matlab? i.e Can anybody help me with the suitable code to compute the p value for the correlation coefficient in R or Matlab?

The output of the calculators available online to compute p value for r is totally different! That's why I am looking for a trusted code to compute it using R or Matlab

Say r <- cor(x, y) n<-length(x)

Two-tailed tests:

1. Testing using Student's t-distribution:

t<-r*sqrt((n-2)/(1-r^2)) p<-2*pt(-abs(t),n-2)

1. Using the Fisher transformation

z<-(atanh(r)-0)*sqrt(n-3) p<-2*pnorm(-abs(z))

You an use the cor.test() function in R to get the p-value.

If you look at the code for the function, by using:

getAnywhere("cor.test.default")


You can see how the p-value is calculated. The important bit is:

r <- cor(x, y)
df <- n - 2L
STATISTIC <- c(t = sqrt(df) * r/sqrt(1 - r^2))
p <- pt(STATISTIC, df)

• @ Jeremey Miles. Thanks! n is the number of variants! what is L refering to? Oct 28, 2014 at 22:00
• The L forces df to be an integer. See stackoverflow.com/questions/7014387/… Oct 28, 2014 at 22:32

In Matlab (http://www.mathworks.nl/help/stats/corr.html),

[RHO,PVAL] = corr(X,Y);


In R, just type

cor.test(x,y)\$p.value

• The p value here is significant if it is less than 0.05? Oct 28, 2014 at 22:04
• If you are testing at the 0.05 level, yes Oct 28, 2014 at 22:09

In R you can use this code (The numbers are an example to show you how to do it):

x <- c(1,2,3,4,5)
y <- c(5,6,7,8,9)
cor.test(x,y)