Zaynab
Zaynab

Reputation: 233

using cor.test function in R

If x be a n*m matrix, when I use cor(x), I have a m*m correlation matrix between each pair of columns.

How can I use cor.test function on the n*m matrix to have a m*m p-value matrix also?

Upvotes: 0

Views: 535

Answers (2)

phargart
phargart

Reputation: 729

Please also see the cor.mtest() function in the corrplot package. https://www.rdocumentation.org/packages/corrplot/versions/0.92/topics/cor.mtest

Upvotes: 0

Dan
Dan

Reputation: 12084

There may be an existing function, but here's my version. p_cor_mat runs cor.test on each pair of columns in matrix x and records the p-value. These are then put into a square matrix and returned.

# Set seed
set.seed(42)

# Matrix of data
x <- matrix(runif(120), ncol = 4)

# Function for creating p value matrix
p_cor_mat <- function(x){
  # All combinations of columns
  colcom <- t(combn(1:ncol(x), 2))

  # Calculate p values
  p_vals <- apply(colcom, MAR = 1, function(i)cor.test(x[,i[1]], x[,i[2]])$p.value)

  # Create matrix for result
  p_mat <- diag(ncol(x))

  # Fill upper & lower triangles
  p_mat[colcom] <- p_mat[colcom[,2:1]] <- p_vals

  # Return result
  p_mat
}

# Test function
p_cor_mat(x)
#>           [,1]      [,2]      [,3]      [,4]
#> [1,] 1.0000000 0.4495713 0.9071164 0.8462530
#> [2,] 0.4495713 1.0000000 0.5960786 0.7093539
#> [3,] 0.9071164 0.5960786 1.0000000 0.7466226
#> [4,] 0.8462530 0.7093539 0.7466226 1.0000000

Created on 2019-03-06 by the reprex package (v0.2.1)

Upvotes: 1

Related Questions