Skip to content

Pearson corelation and p-value for matrix

2 messages · Liaw, Andy, John Fox

#
We can be a bit sneaky and `borrow' code from cor.test.default:

cor.pval <- function(x,  alternative="two-sided", ...) {
    corMat <- cor(x, ...)
    n <- nrow(x)
    df <- n - 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
}

The test:
[1] 13.19  0.01 13.58    NA    NA
[1] 6.22 0.00 6.42   NA   NA
[1] 0.07 0.00 0.07   NA   NA

Cheers,
Andy
#
Dear Andy,

That's clearly much better -- and illustrates an effective strategy for
vectorizing (or "matricizing") a computation. I think I'll add this to my
list of programming examples. It might be a little dangerous to pass ...
through to cor(), since someone could specify type="spearman", for example.

Thanks,
 John

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