Search code examples
rcorrelationperformanceanalyticsggpairs

Is there an R function to export the correlations showed in a correlation matrix?


I have created a correlation matrix with ggpairs, with my data grouped by factor. However I can't extract the correlations presented (I'm interested in the contribution of each factor to the overall correlation, as well as it's significance)

I created a correlation matrix using both ggpairs and another using PerformanceAnalytics. I tried as well calculating the correlations as well as the p-value (no luck here) for each of factor.

ggpairs(s1[,4:12], aes(colour = s1$media), title = "1308", upper=list(
continuous=wrap("cor", size = 2.3)))

chart.Correlation(s1[,4:6], histogram=TRUE, pch=19,cex.labels=0.3, method = "s")

I also tried to calculate the correlations and p-values, but for the p-values my loop stops at the first matrix

for(l in levels(s1[,3])){
   cor.by.treat[[l]]<-(cor(s1[which(s1[,1]==l),4:12],
                           use="complete.obs", method = "spearman"))
 }
pcor.by.treat <- list()  
>  for(l in levels(s1[,1])){
     pcor.by.treat[[l]]<-(cor.mtest(s1[which(s1[,1]==l),4:12],                                      
  method = "spearman", use="complete.obs"))
 }

a subset of the data can be found here

I'd like to visualise my data as in ggpairs, but with the significance (as in chart.Correlation). Is there a way to extract the content of the upper part?

The correlation matrices aren't really an option as I have 10 other subsets like the one provided, and I'd appreciate to keep the main correlation and it's components together.


Solution

  • try this one,

    
    data_list <- split(s1, s1$media)
    p_value <- lapply(data_list, function(x) corrplot::cor.mtest(x[, 4:12])[["p"]])
    correlation <- lapply(data_list, function(x) cor(x[, 4:12], method = "spearman"))
    

    This will give you a list of p_value and correlation grouped by media. Instead of media you can use medium.strain as well.