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

批量生成多列与Factor1的列联表并执行Fisher精确检验,提取显著P值

批量执行Fisher精确检验并提取显著结果

数据准备

首先注意你的原始数据中重复定义了col9列,会导致后定义的覆盖前一个,先修正数据框:

df_out <- data.frame(
    "name" = c("1", "2", "3", "4", "5", "6", "7", "8"),
    "Factor1"=rep(c("A","B","C"),times= c(2,1,5)),
    "col2"=rep(c("A","G"),times= c(4,4)),
    "col3"=rep(c("T","S"),times= c(2,6)),
    "col4"=rep(c("E","D"),times= c(6,2)),
    "col5"=rep(c("N","A","R"),times= c(4,2,2)),
    "col6"=rep(c("B","O"),times= c(1,7)),
    "col7"=rep(c("N","A","R","L"),times= c(1,3,2,2)),
    "col8"=rep(c("I","V","R"),times= c(2,4,2)),
    "col9_1"=rep(c("I","G","R"),times= c(1,6,1)), # 重命名避免覆盖
    "col9_2"=rep(c("F","L","N"),times= c(5,2,1)),
    "col10"=rep(c("T","C","R"),times= c(3,2,3))
)

批量处理步骤

  • 加载所需包
library(rstatix)
library(dplyr) # 可选,用于数据整理
  • 定义需要检验的列(排除name和Factor1)
test_cols <- setdiff(names(df_out), c("name", "Factor1"))
  • 批量生成列联表并执行Fisher检验
    我们用lapply循环处理每一列,同时保存列联表和检验结果:
# 存储结果的列表
result_list <- lapply(test_cols, function(col) {
  # 生成列联表
  contingency_table <- table(df_out$Factor1, df_out[[col]])
  # 执行Fisher检验
  fisher_result <- fisher_test(contingency_table, detailed = TRUE)
  # 返回包含列名、列联表、检验结果的列表
  list(
    column_name = col,
    contingency_table = contingency_table,
    fisher_test_result = fisher_result
  )
})

# 给列表命名,方便查看
names(result_list) <- test_cols
  • 提取显著的P值(以α=0.05为例)
# 筛选出P值小于0.05的结果
significant_results <- Filter(function(x) {
  x$fisher_test_result$p < 0.05
}, result_list)

# 整理成数据框展示
significant_p_values <- do.call(rbind, lapply(significant_results, function(x) {
  data.frame(
    column = x$column_name,
    p_value = x$fisher_test_result$p,
    p_adjusted = x$fisher_test_result$p.adj # 可选,校正后的P值
  )
}))

print(significant_p_values)

补充说明

  • 若需调整显著性阈值,修改Filter函数中的0.05即可
  • 单独查看某一列的列联表:result_list[[col_name]]$contingency_table
  • 结果中的p.adj是多重检验校正后的P值,可直接用于控制假阳性率

内容的提问来源于stack exchange,提问作者Marwah Al-kaabi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:35:42