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

如何对多组连续频数表执行卡方检验(Chi-squared test)

连续频数表的卡方检验实现方案

数据集定义

首先定义主数据框df及各阶段的筛选数据框:

df = data.frame(x = seq(1,20,2),
                y = c('a','a','b','c','a','a','b','c','a','a'),
                z = c('d','e','e','d','f','e','e','d','e','f') )

stage1 = data.frame(xx = c(2,3,4,5,7,8,9) )
stage2 = data.frame(xx = c(3,5,7,8,9) )
stage3 = data.frame(xx = c(2,3,6,8) )
stage4 = data.frame(xx = c(1,3,6) )

生成各阶段频数表

使用dplyr和purrr生成每个stage对应的y变量频数表:

library(dplyr)
library(purrr)

# 生成各stage的y频数表
freq_tables <- map(lst(stage1 , stage2 ,stage3 ,stage4 ), 
                   ~ inner_join(df, .x, by = c("x" = "xx")) %>%      
                       count(y, name = 'Count'))

连续组的卡方检验实现

要对连续两组的频数表做卡方检验,需先统一频数表的类别维度,再遍历所有连续组对执行检验:

# 获取y的所有唯一类别,确保各组频数表维度一致
all_y_levels <- unique(df$y)

# 补全每个频数表的y类别,缺失类别对应的Count设为0
freq_tables_full <- map(freq_tables, function(tbl) {
  tibble(y = all_y_levels) %>%
    left_join(tbl, by = "y") %>%
    mutate(Count = replace_na(Count, 0)) %>%
    arrange(y)
})

# 生成连续组的索引对(如stage1&stage2、stage2&stage3等)
pair_indices <- map2(seq_along(freq_tables_full)[-length(freq_tables_full)],
                     seq_along(freq_tables_full)[-1],
                     ~ c(.x, .y))

# 遍历每组对执行卡方检验
chi_sq_results <- map(pair_indices, function(idx) {
  # 提取两组的频数数据
  group1_counts <- freq_tables_full[[idx[1]]]$Count
  group2_counts <- freq_tables_full[[idx[2]]]$Count
  
  # 构建列联表
  contingency_table <- rbind(group1_counts, group2_counts)
  colnames(contingency_table) <- all_y_levels
  rownames(contingency_table) <- names(freq_tables_full)[idx]
  
  # 执行卡方检验
  test_result <- chisq.test(contingency_table)
  
  # 返回包含对比信息、列联表和检验结果的列表
  list(
    comparison_group = paste(names(freq_tables_full)[idx], collapse = " vs "),
    contingency_table = contingency_table,
    chi_square_test = test_result
  )
})

# 查看所有检验结果
chi_sq_results

关键说明

  • 补全y类别是为了避免部分组缺少某些类别导致列联表维度不匹配,进而卡方检验报错
  • 检验结果包含对比组名称、列联表、卡方值、自由度及p值,可直接用于判断组间差异的统计学显著性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:55:18