You need to enable JavaScript to run this app. 多条件约束下1:2不重复病例对照匹配的R实现求助
优惠活动
大模型
产品
解决方案
定价
更多

多条件约束下1:2不重复病例对照匹配的R实现求助

R实现病例对照无放回匹配代码

匹配规则说明

  • 每个case最多匹配2个独立control,已匹配的control不会被其他case复用
  • 匹配条件:两组age差值≤2,income差值≤2
  • 符合条件的control超过2个时,随机抽取2个

实现代码

# 依赖包安装(首次运行先执行)
# install.packages("tidyverse")
library(tidyverse)

# 示例数据集
dat = structure(list(id = c(1, 2, 3, 4, 111, 222, 333, 444, 555, 666, 777, 888, 999, 1000), 
                     age = c(10, 20, 44, 11, 12, 11, 8, 12, 11, 22, 21, 18, 21, 18), 
                     income = c(35, 72, 11, 35, 37, 36, 33, 70, 34, 74, 70, 44, 76, 70), 
                     group = c("case", "case", "case", "case", "control", "control", "control", "control", "control", "control", "control", "control", "control", "control")), 
                row.names = c(NA, -14L), class = c("tbl_df", "tbl", "data.frame"))

# 拆分case和对照池
case_df <- filter(dat, group == "case")
control_pool <- filter(dat, group == "control")

# 初始化结果存储
match_result <- list()

# 设置随机种子保证结果可复现,可修改参数获得不同随机抽样结果
set.seed(123)

# 可选优化:预计算每个case的可用对照数量,优先匹配难匹配的case,避免对照资源被提前占用
case_df <- case_df %>%
  rowwise() %>%
  mutate(eligible_n = sum(abs(control_pool$age - age) <=2 & abs(control_pool$income - income) <=2)) %>%
  arrange(eligible_n) %>%
  select(-eligible_n)

# 遍历每个case完成匹配
for (i in 1:nrow(case_df)) {
  current_case <- case_df[i, ]
  
  # 筛选符合差值要求的可用对照
  eligible_controls <- control_pool %>%
    filter(abs(age - current_case$age) <= 2,
           abs(income - current_case$income) <= 2)
  
  if (nrow(eligible_controls) == 0) {
    # 无符合条件的对照,标记匹配失败
    match_result[[i]] <- tibble(case_id = current_case$id, control_id = NA, match_status = "无符合条件对照")
    next
  }
  
  # 不足2个则取全部,够2个则随机抽2个
  sample_n <- min(2, nrow(eligible_controls))
  selected_controls <- sample_n(eligible_controls, sample_n)
  
  # 存储匹配结果
  match_result[[i]] <- tibble(
    case_id = current_case$id,
    case_age = current_case$age,
    case_income = current_case$income,
    control_id = selected_controls$id,
    control_age = selected_controls$age,
    control_income = selected_controls$income,
    match_status = "匹配成功"
  )
  
  # 从对照池中移除已匹配的对照,避免重复使用
  control_pool <- filter(control_pool, !id %in% selected_controls$id)
}

# 合并输出最终结果
final_result <- bind_rows(match_result)
print(final_result)

结果说明

示例数据中id为3的case(age=44,income=11)无符合条件的对照,会返回匹配失败标记,其余case均可匹配到2个不重复的对照。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 08:06:02