A matrix version of cor.test()

后端 未结 5 1117
有刺的猬
有刺的猬 2020-11-27 03:23

Cor.test() takes vectors x and y as arguments, but I have an entire matrix of data that I want to test, pairwise. Cor() t

5条回答
  •  一向
    一向 (楼主)
    2020-11-27 04:00

    If you're strictly after the pvalues in a matrix format from cor.test here's a solution shamelessly stolen from Vincent (LINK):

    cor.test.p <- function(x){
        FUN <- function(x, y) cor.test(x, y)[["p.value"]]
        z <- outer(
          colnames(x), 
          colnames(x), 
          Vectorize(function(i,j) FUN(x[,i], x[,j]))
        )
        dimnames(z) <- list(colnames(x), colnames(x))
        z
    }
    
    cor.test.p(mtcars)
    

    Note: Tommy also provides a faster solution though less easy to impliment. Oh and no for loops :)

    Edit I have a function v_outer in my qdapTools package that makes this task pretty easy:

    library(qdapTools)
    (out <- v_outer(mtcars, function(x, y) cor.test(x, y)[["p.value"]]))
    print(out, digits=4)  # for more digits
    

提交回复
热议问题