R语言生成含3位小数的Spearman相关矩阵及添加显著性标记的技术问题
R语言生成含3位小数的Spearman相关矩阵及添加显著性标记的技术问题
嗨,我来帮你搞定这两个折腾了你好几个小时的问题!
一、生成带3位小数+显著性标记的Spearman相关矩阵
我推荐用psych包来处理,它能一次性输出相关系数和对应的p值,方便后续格式化处理;当然用基础R或者你之前尝试的Hmisc也能搞定,下面分两种方法说明:
方法1:用psych包(更高效)
psych包的corr.test函数可以直接计算Spearman相关并返回p值矩阵,步骤如下:
# 先加载包(如果没安装先运行install.packages("psych")) library(psych) # 假设你的数据存储在数据框df中,替换成你的实际数据对象名 df <- your_data_frame # 计算Spearman相关系数和对应的p值(adjust参数可根据需求调整多重比较校正方法,比如"holm") cor_results <- corr.test(df, method = "spearman", adjust = "none") # 提取相关系数矩阵和p值矩阵 cor_matrix <- cor_results$r p_matrix <- cor_results$p
接下来我们写一个自定义函数,给系数加上3位小数和显著性标记(p<0.05加*,p<0.1加+,注意优先标记更显著的*):
# 定义格式化函数 format_cor_with_signif <- function(cor_val, p_val) { # 保留3位小数 rounded_cor <- round(cor_val, 3) # 添加显著性标记 if (p_val < 0.05) { paste0(rounded_cor, "*") } else if (p_val < 0.1) { paste0(rounded_cor, "+") } else { as.character(rounded_cor) } } # 把函数应用到整个矩阵,恢复行名列名 formatted_cor_matrix <- mapply(format_cor_with_signif, cor_matrix, p_matrix) dim(formatted_cor_matrix) <- dim(cor_matrix) rownames(formatted_cor_matrix) <- rownames(cor_matrix) colnames(formatted_cor_matrix) <- colnames(cor_matrix)
现在formatted_cor_matrix就是你要的带3位小数和显著性标记的矩阵啦!
方法2:用Hmisc包(解决你之前的问题)
你之前用Hmisc没得到3位小数,其实是需要手动提取并格式化相关系数:
# 加载包(没安装先运行install.packages("Hmisc")) library(Hmisc) # 计算Spearman相关 rcorr_results <- rcorr(as.matrix(df), type = "spearman") # 把相关系数保留3位小数 rounded_cor <- round(rcorr_results$r, 3) # 同样用上面的format_cor_with_signif函数结合p值添加标记 formatted_cor_matrix <- mapply(format_cor_with_signif, rounded_cor, rcorr_results$P) dim(formatted_cor_matrix) <- dim(rounded_cor) rownames(formatted_cor_matrix) <- rownames(rounded_cor) colnames(formatted_cor_matrix) <- colnames(rounded_cor)
二、导出格式化后的系数矩阵
直接用基础R的write.csv或者write.table就能导出到文件:
# 导出到CSV文件,row.names=TRUE保留行名 write.csv(formatted_cor_matrix, "spearman_correlation_with_signif.csv", row.names = TRUE)
三、关于Spearman相关的其他包推荐
除了上面提到的psych和Hmisc,还有这些实用的包:
ggcorrplot:适合可视化相关矩阵,能把显著性标记直接画在图上;corrr:专门用于相关矩阵的整理和可视化,语法更简洁,适合快速探索。
不过如果只是需要计算和导出数值,psych包的功能已经完全够用啦。
备注:内容来源于stack exchange,提问作者Natália
相关产品推荐
相关产品推荐

