# Selecting and visualizing only significant correlation coefficients in matrix

You have:

1) a matrix of correlation coefficients (e.g., matrix A)

2) a matrix of their p-values (e.g., matrix B)

You want to:

1) visualize the correlation coefficients in a correlogram

2) visualize the coefficients **with only significant p-values**

What to do:

install.packages(“psych”)

library(psych)

output = corr.test(rawData)

names(output) # to take a look at the available output statistics

A = output$r # matrix A here contains the correlation coefficients

B = output$p # matrix B here contains the corresponding p-values

# first, to visualize the entire matrix in a correlogram

install.packages(“corrgram”)

library(corrgram)

corrgram(A) # visualizing the correlation coefficients corrgram(B) # visualizing the p-values

# But, you also want to visualize the correlation coefficients with significant p-values!

# to do that, you need to select only the matrix elements with significant p-values

# if it is above 0.05 (not significant), then replace with NAs)

sig_element = ifelse(B < 0.05, A, NA)

# can plot the new matrix

corrgram(sig_element) # this displays only the correlation coefficients that have significant p-values

Note: If you have NA’s in your matrix, sometimes corrgram might not be able to visualize your matrix. This may be due to the NA’s that are present in the diagonals. Replace the NA’s in the diagonals with 1’s and you might be able fix that issue (e.g., diag(A) = 1)

**Updated:
Better Alternative for plotting:
**plot with cor.plot also from the psych package – I realized that it is more flexible as it handles missing values (NAs) better than the corrgram().

cor.plot(sig_element)

# or

cor.plot(sig_element, show.legend = TRUE, main = “title”, numbers = TRUE, labels = names)

**CAUTION:** Please be careful when calculating multiple correlation coefficients. Please correct for multiple comparisons when appropriate!

For more information, please check out:

http://stackoverflow.com/questions/12042309/compare-two-matrices-with-criteria-in-r

http://fortheloveof.co.uk/2010/04/11/r-select-specific-elements-or-find-their-index-in-a-vector-or-a-matrix/

Check out other useful **R tips and tricks** here!