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

如何按状态和性别提取多组cor.test的估计值与p值?

解决方案

方法一:用tidyverse + broom包(推荐)

这个方法能一次性处理所有分组,自动整理检验结果到数据框:

library(tidyverse)
library(broom)

# 假设你的数据集名为df,包含status、gender、X、Y四列
final_df <- df %>%
  # 按status和gender双重分组
  group_by(status, gender) %>%
  summarize(
    # 对每组执行Spearman检验,结果存为列表
    cor_test = list(cor.test(X, Y, method = "spearman")),
    .groups = "drop"
  ) %>%
  # 将检验结果转换为结构化数据框
  mutate(tidy_result = map(cor_test, tidy)) %>%
  unnest(tidy_result) %>%
  # 筛选并重命名需要的列
  select(
    Status = status,
    Gender = gender,
    `Estimate(rho)` = estimate,
    `P-value` = p.value
  )

# 查看结果
final_df

方法二:base R原生实现

如果不想加载额外包,可以用by()函数分组处理:

# 按status和gender分组执行检验
grouped_results <- by(
  data = df,
  INDICES = list(df$status, df$gender),
  FUN = function(sub_data) {
    res <- cor.test(sub_data$X, sub_data$Y, method = "spearman")
    # 提取需要的结果并组装数据框
    data.frame(
      Status = unique(sub_data$status),
      Gender = unique(sub_data$gender),
      `Estimate(rho)` = res$estimate,
      `P-value` = res$p.value,
      stringsAsFactors = FALSE
    )
  }
)

# 合并所有分组结果
final_df <- do.call(rbind, grouped_results)

为什么你之前用data.frame会报错?

cor.test()返回的是一个列表对象,直接用data.frame()转换会因为结构不兼容报错。必须手动提取列表中的estimate(rho值)和p.value元素,或者用broom::tidy()自动将检验结果转为标准数据框格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:31:11