Skip to content

Pearson corelation and p-value for matrix

2 messages · Liaw, Andy, John Fox

#
I believe this will do:

cor.pval2 <- function(x,  alternative="two-sided") {
    corMat <- cor(x, use=if (any(is.na(x))) "pairwise.complete.obs" else
"all")
    df <- crossprod(!is.na(x)) - 2
    STATISTIC <- sqrt(df) * corMat / sqrt(1 - corMat^2)
    p <- pt(STATISTIC, df)
    p <- if (alternative == "less") {
        p
    } else if (alternative == "greater") {
        1 - p
    } else 2 * pmin(p, 1 - p)
    p
}

Some test:
[1] 17.28  0.77 18.16    NA    NA
[1] 19.51  1.05 20.70    NA    NA
[1] 0
[1] 24.48  0.71 25.28    NA    NA

This is a bit slower because of the extra computation for "df".  One can try
to save some computation by only computing with the lower (or upper)
triangular part.

Cheers,
Andy
#
Dear Andy,

Very nice! (My point was that if this is a one-time thing, for Dren to
puzzle over it is probably more time-consuming than simply doing it
inefficiently.)

Regards,
 John

--------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario
Canada L8S 4M4
905-525-9140x23604
http://socserv.mcmaster.ca/jfox 
--------------------------------