You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用psych包的corr.test计算两数据框对应列的相关性及显著性

使用psych包的corr.test计算两个数据框对应列的相关性与显著性

实现步骤

首先确保安装并加载psych包:

if (!require(psych)) install.packages("psych")
library(psych)

加载示例数据:

set.seed(42)
Df1 <- data.frame(matrix(runif(50), 10, 5))
Df2 <- data.frame(matrix(runif(50), 10, 5))

方法1:用mapply批量处理对应列

通过mapply遍历两个数据框的对应列,对每一列对应用corr.test,提取相关性系数和显著性p值:

# 批量计算每对列的相关与显著性
col_pair_results <- mapply(function(x, y) {
  ct <- corr.test(x, y)
  # 提取关键结果
  data.frame(
    correlation = ct$r[1,2],
    p_value = ct$p[1,2],
    sample_size = ct$n[1,2]
  )
}, Df1, Df2, SIMPLIFY = FALSE)

# 合并为统一的数据框并标注列对
final_results <- do.call(rbind, col_pair_results)
rownames(final_results) <- paste0("Pair ", seq_len(ncol(Df1)), ": Df1-Col", seq_len(ncol(Df1)), " vs Df2-Col", seq_len(ncol(Df1)))

查看输出结果:

print(final_results)

方法2:用for循环实现(更直观)

如果更喜欢循环逻辑,也可以用for循环逐个处理列对:

results_list <- list()
for (i in 1:ncol(Df1)) {
  test_out <- corr.test(Df1[[i]], Df2[[i]])
  results_list[[i]] <- data.frame(
    column_pair = paste("Df1-Col", i, "& Df2-Col", i),
    pearson_cor = test_out$r[1,2],
    p_value = test_out$p[1,2],
    n = test_out$n[1,2]
  )
}

final_results_loop <- do.call(rbind, results_list)

自定义相关方法

corr.test默认使用Pearson相关,若需要Spearman或Kendall秩相关,只需添加method参数:

# 示例:计算Spearman相关
spearman_test <- corr.test(Df1[[1]], Df2[[1]], method = "spearman")

内容的提问来源于stack exchange,提问作者Arturo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:20:28