0
$\begingroup$

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

$\endgroup$
1

5 Answers 5

5
$\begingroup$

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))

$\endgroup$
3
$\begingroup$

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)
$\endgroup$
2
  • 1
    $\begingroup$ @ Jeremey Miles. Thanks! n is the number of variants! what is L refering to? $\endgroup$
    – dr.green
    Commented Oct 28, 2014 at 22:00
  • 1
    $\begingroup$ The L forces df to be an integer. See stackoverflow.com/questions/7014387/… $\endgroup$ Commented Oct 28, 2014 at 22:32
2
$\begingroup$

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

[RHO,PVAL] = corr(X,Y);
$\endgroup$
1
$\begingroup$

In R, just type

cor.test(x,y)$p.value
$\endgroup$
2
  • $\begingroup$ The p value here is significant if it is less than 0.05? $\endgroup$
    – dr.green
    Commented Oct 28, 2014 at 22:04
  • 1
    $\begingroup$ If you are testing at the 0.05 level, yes $\endgroup$
    – Arthur B.
    Commented Oct 28, 2014 at 22:09
1
$\begingroup$

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)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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