# 两个独立组的二分类结局：输入 huyiba_rawdata，每行一个观察单位。
group_var <- "group"
outcome_var <- "outcome"
group_levels <- c("reference", "comparison")
outcome_levels <- c("no", "yes") # 第 2 列是阳性；行百分比按各组人数计算。
test_method <- "auto"           # "pearson" 固定用卡方；"fisher" 固定用确切检验。
min_expected <- 5               # auto 的 2×2 表经验线：任一格低于此值用 Fisher。
correct <- FALSE                # 仅影响卡方；TRUE 加 Yates 连续性校正。
conf_level <- 0.95              # 仅用于 Fisher 的 OR 区间；提高时区间通常更宽。

# 明确类别顺序，避免无效编码被因子转换后静默丢弃。
input_columns <- c(group_var, outcome_var)
if (anyDuplicated(input_columns) || !all(input_columns %in% names(huyiba_rawdata))) {
  stop("分组列和结局列必须存在且不同。")
}
huyiba_analysis_data <- huyiba_rawdata[input_columns]
group_values <- as.character(huyiba_analysis_data[[group_var]])
outcome_values <- as.character(huyiba_analysis_data[[outcome_var]])
if (anyNA(huyiba_analysis_data) ||
    length(group_levels) != 2L || length(outcome_levels) != 2L ||
    !setequal(group_values, group_levels) ||
    !setequal(outcome_values, outcome_levels)) {
  stop("请提供完整数据；分组和结局必须各有两个实际出现且与配置一致的类别。")
}
observed <- table(
  group = factor(group_values, levels = group_levels),
  outcome = factor(outcome_values, levels = outcome_levels)
)
expected <- outer(rowSums(observed), colSums(observed)) / sum(observed)
dimnames(expected) <- dimnames(observed)

# 先看期望频数，再按预设方案选择检验；两个分支均为双侧的独立性问题。
test_method <- match.arg(test_method, c("auto", "pearson", "fisher"))
if (test_method == "auto") {
  test_method <- if (any(expected < min_expected)) "fisher" else "pearson"
}
test_result <- if (test_method == "pearson") {
  stats::chisq.test(observed, correct = correct)
} else {
  stats::fisher.test(
    observed, alternative = "two.sided", conf.level = conf_level
  )
}

# row_proportion 是 0–1 的组内比例；Fisher OR 方向为第 2 组相对第 1 组。
huyiba_result <- list(
  observed = observed, expected = expected,
  row_proportion = prop.table(observed, margin = 1),
  method = test_method, test = test_result
)
print(huyiba_result$observed)
print(huyiba_result$expected)
print(huyiba_result$row_proportion)
print(huyiba_result$test)
