R语言矩阵相关性计算及其可视化?
卖萌控的博客
点击这里进入电脑版页面!体验更好
R语言矩阵相关性计算及其可视化?
2022-10-3 萌小白


目录



  • 1. 矩阵相关性计算方法


    • base::cor/cor.test


    • psych::corr.test


    • Hmisc::rcorr


    • 其他工具




  • 2. 相关性矩阵转化为两两相关


  • 3. 可视化


    • corrplot


    • gplots::heatmap.2


    • pheatmap






1. 矩阵相关性计算方法



base::cor/cor.test



R基础函数cor或cor.test都可计算相关性系数,但cor可直接计算矩阵的相关性,而cor.test不可。



两者计算非矩阵时,cor仅得到相关系数,而cor.test还能得到pvalue。






  1. library(ggplot2)



  2. cor(mtcars)



  3. cor.test(mtcars) #error



  4. cor.test(mtcars,mtcars) #error







  5. cor(mtcars$mpg,mtcars$cyl) #only cor



  6. x=cor.test(mtcars$mpg,mtcars$cyl) #cor and pvalue



  7. x$estimate



  8. x$p.value





可以用基础函数cor得到相关性矩阵,再自己编写脚本获得pvalue矩阵。






  1. M = cor(mtcars)



  2. #自编写函数得到pvalue矩阵



  3. cor.mtest <- function(mat, ...) {



  4. mat <- as.matrix(mat)



  5. n <- ncol(mat)



  6. p.mat<- matrix(NA, n, n)



  7. diag(p.mat) <- 0



  8. for (i in 1:(n - 1)) {



  9. for (j in (i + 1):n) {



  10. tmp <- cor.test(mat[, i], mat[, j], ...)



  11. p.mat[i, j] <- p.mat[j, i] <- tmp$p.value



  12. }



  13. }



  14. colnames(p.mat) <- rownames(p.mat) <- colnames(mat)



  15. p.mat



  16. }



  17. matrix_p=cor.mtest(mtcars)











psych::corr.test



使用psych包中的corr.test函数,可直接获得矩阵相关性系数和pvalue(也可用于非矩阵),而且还可直接得到矫正后的pvalue。






  1. library(psych)







  2. corr.test(mtcars)



  3. cor <- corr.test(mtcars,



  4. method = "pearson",



  5. adjust = "fdr") #同p.adjust函数



  6. cor$r



  7. cor$p



  8. cor$p.adj #但得到的是向量,数目也不对



  9. test <- p.adjust(cor$p,method = "fdr")



  10. identical(cor$p.adj,test) #不等




















Hmisc::rcorr



使用Hmisc包中的rcorr函数,直接得到相关性系数和pvalue矩阵。






  1. library(Hmisc)



  2. #注意要将数据框转换为矩阵



  3. cor.mat <- rcorr(as.matrix(mtcars), type = "pearson")



  4. cor.mat$r



  5. cor.mat$P













可视化时,pvalue矩阵对角线的显著性我们不必要展示,可以替换下。另外,如果后续不展示全部矩阵,只展示过了设置条件的部分,则可进行过滤。






  1. # # only keep comparisons that have some abs. correlation >= .5 (optional)



  2. # keep <- rownames(cor.mat$r)[rowSums(abs(cor.mat$r)>=0.5) > 1]



  3. # cor.mat <- lapply(cor.mat, function(x) x[keep, keep])







  4. # set diagonal to 1, since it is not interesting and should not be marked



  5. diag(cor.mat$P) <- 1





其他工具



其他还有工具,如ggcor + ggcorrplot, 但不建议使用,增加学习成本,以上方法足以成对所有情况。



另外统计和绘图R包rstatix也可计算相关矩阵,显示和标记显著性水平,而且可以gather和spread相关性矩阵,可tidyverse语法类似。这个包值得好好学习:https://rpkgs.datanovia.com/rstatix/index.html



2. 相关性矩阵转化为两两相关



一般来说,我们得到的是相关性系数矩阵和pvalue矩阵,但输出数据时最好转换为两两之间的行列式格式。



这种转换以上的rstatix包可轻松解决。



请参考:https://rpkgs.datanovia.com/rstatix/reference/cor_reshape.html



另外,我们也可自己编写脚本得到:






  1. flattenCorrMatrix <- function(cormat, pmat) {



  2. ut <- upper.tri(cormat)



  3. data.frame(



  4. row = rownames(cormat)[row(cormat)[ut]],



  5. column = rownames(cormat)[col(cormat)[ut]],



  6. cor =(cormat)[ut],



  7. p = pmat[ut]



  8. )



  9. }



  10. res <- flattenCorrMatrix(cor.mat$r, cor.mat$P)



  11. res








3. 可视化



得到了相关性和pvalue两个矩阵,我们一般以热图展示为好。



corrplot



经典的相关性展示工具。很多可选样式:https://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html



我仅展示几个案例,更多参数自己调节。






  1. #仅cor



  2. corrplot.mixed(M)







  3. #cor,仅0.05



  4. corrplot.mixed(M,



  5. insig = 'label_sig',



  6. p.mat=matrix_p,



  7. pch.cex = 0.9,



  8. pch.col = 'grey20')







  9. #细分



  10. corrplot(M,



  11. p.mat = matrix_p,



  12. tl.pos = 'd',



  13. order = 'hclust',



  14. type = "upper",



  15. #addrect = 2,



  16. insig = 'label_sig',



  17. sig.level = c(0.001, 0.01, 0.05),



  18. pch.cex = 0.9,



  19. pch.col = 'grey20')
















gplots::heatmap.2



相对于上图,我更喜欢用热图来展示。






  1. library(RColorBrewer)



  2. library(gplots)



  3. my_palette <- colorRampPalette(c("blue","white","red")) (100)







  4. # plot heatmap and mark cells with abs(r) >= .5 and p < 0.05



  5. heatmap.2(cor.mat$r,



  6. # cexRow = .35, cexCol = .35,



  7. trace = 'none',



  8. # key.title = 'Spearman correlation',



  9. # keysize = .5, key.par = list(cex=.4),



  10. notecol = 'black', srtCol = 30,



  11. col = my_palette,



  12. cellnote = ifelse(cor.mat$P < 0.05 & abs(cor.mat$r)>=0.5, "*", ""))









以上我仅标出相关性绝对值大于0.5,pvalue<0.05的数据。当然可以做更细致划分。



pheatmap



pheatmap参数更好调些,看个人喜好。






  1. #pheatmap



  2. pheatmap(cor.mat$r,



  3. color = my_palette,



  4. display_numbers = ifelse(cor.mat$P < 0.05 & abs(cor.mat$r)>=0.5, "*", ""))









Ref:



https://www.jianshu.com/p/b76f09aacd9c



https://chowdera.com/2020/12/20201218185101270B.html



https://stackoverflow.com/questions/66305232/r-how-to-plot-a-heatmap-that-shows-significant-correlations



http://www.sthda.com/english/wiki/correlation-matrix-an-r-function-to-do-all-you-need



http://www.sthda.com/english/wiki/correlation-matrix-a-quick-start-guide-to-analyze-format-and-visualize-a-correlation-matrix-using-r-software








发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容