rmatrixcorrelationr-corrplot

How to replace values ​in a matrix based on a conditional variable


I have this data:

data(mtcars)
correlation_matrix <- cor(mtcars)
      
matcor <- cor(correlation_matrix, method = "spearman") #Faz a correlations
print(matcor, digits = 2) #Exibe as correlations
library(corrplot)
testRes = cor.mtest(correlation_matrix, method = "spearman") 
## GRAFICO CORRELATION ##
col <- colorRampPalette(c("#FFFFFF","#FFFFFF","#FFFFFF" ,"#FFFFFF", "#F4A460", "#CD6839")) #Atribui cores ao grafico
corrplot(matcor, p.mat = testRes$p, method="color", sig.level = c(0.001, 0.01, 0.05), pch.cex = 0.9,
         insig = 'label_sig', pch.col = 'white',col=col(100), diag=FALSE,  tl.col = "black")

this give me :

print(matcor, digits = 2) #Exibe as correla??es

      mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
mpg   1.00 -0.91 -0.95 -0.81  0.89 -0.96  0.55  0.75  0.84  0.77 -0.68
cyl  -0.91  1.00  0.95  0.95 -0.74  0.84 -0.78 -0.93 -0.66 -0.56  0.80
disp -0.95  0.95  1.00  0.86 -0.84  0.92 -0.62 -0.82 -0.80 -0.73  0.68
hp   -0.81  0.95  0.86  1.00 -0.63  0.74 -0.90 -0.95 -0.55 -0.42  0.89
drat  0.89 -0.74 -0.84 -0.63  1.00 -0.95  0.38  0.60  0.96  0.92 -0.55
wt   -0.96  0.84  0.92  0.74 -0.95  1.00 -0.45 -0.65 -0.91 -0.86  0.60
qsec  0.55 -0.78 -0.62 -0.90  0.38 -0.45  1.00  0.92  0.25  0.10 -0.93
vs    0.75 -0.93 -0.82 -0.95  0.60 -0.65  0.92  1.00  0.52  0.39 -0.90
am    0.84 -0.66 -0.80 -0.55  0.96 -0.91  0.25  0.52  1.00  0.97 -0.43
gear  0.77 -0.56 -0.73 -0.42  0.92 -0.86  0.10  0.39  0.97  1.00 -0.25
carb -0.68  0.80  0.68  0.89 -0.55  0.60 -0.93 -0.90 -0.43 -0.25  1.00

Now I need that where the correlations do not have a value of "testRes$p" greater than 0.05 the value in the correlation matrix is ​​replaced by 0.

I try:

 newcor<- ifelse(testRes$p >= 0.05, matcor, 0)

Solution

  • Here's one way to do it:

    newcor <- matcor
    newcor[testRes$p < 0.05] <- 0