Skip to content
Prev 67818 / 398506 Next

Pearson corelation and p-value for matrix

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