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

按疗效处理患者-药物给药数据:统计不同药物的治愈/未治愈患者数

问题:按药物分组统计治愈与未治愈的唯一患者数量

我有一个包含药物列表、给药日期、患者信息以及逻辑型疗效字段(headache_cured:TRUE/FALSE)的数据框,想要生成一个新数据框,每行对应一种药物,统计使用该药物的治愈和未治愈的唯一患者数量。

示例输入数据

R代码生成输入数据

patient_id <- c("a","a","b","c","d","d","d")
drug <- c("tylenol", "tylenol", "tylenol", "advil", "aspirin", "aspirin", "motrin")
date <- c("1/1/2000", "1/2/2000", "1/3/2000", "1/4/2000", "1/5/2000", "1/6/2000", "1/7/2000")
headache_cured <- c(T,T,T,T,F,F,F)

df <- data.frame(patient_id,date,drug,headache_cured)

输入数据表格

patient_iddatedrugheadache_cured
a1/1/2000tylenolTRUE
a1/2/2000tylenolTRUE
b1/3/2000tylenolTRUE
c1/4/2000advilTRUE
d1/5/2000aspirinFALSE
d1/6/2000aspirinFALSE
d1/7/2000motrinFALSE

期望输出数据

注:原示例中aspirin的未治愈患者数存在笔误,修正后正确输出如下

drugn_patients_curedn_patients_not_cured
tylenol20
aspirin01
motrin01
advil10

尝试的错误代码

df %>%
mutate(n_patients_cured = ifelse(headache_cured == T, n_distinct(patient_id),0) %>%
mutate(n_patients_not_cured = ifelse(headache_cured == F, n_distinct(patient_id),0)

解决方案

你的代码存在两个核心问题:

  1. 未按药物分组,n_distinct会计算整个数据框的唯一患者数,而非单种药物分组内的数量
  2. 缺少闭合括号,存在语法错误

推荐使用dplyr包完成需求,核心步骤是先去重(避免同一患者同药物被重复计数),再分组统计:

方法1:group_by + summarize

library(dplyr)

result <- df %>%
  # 去重:保留每个患者-药物-治愈状态的唯一记录
  distinct(patient_id, drug, headache_cured, .keep_all = FALSE) %>%
  # 按药物分组
  group_by(drug) %>%
  # 统计治愈/未治愈的患者数量
  summarize(
    n_patients_cured = sum(headache_cured == TRUE),
    n_patients_not_cured = sum(headache_cured == FALSE)
  ) %>%
  # 取消分组状态
  ungroup()

print(result)

方法2:count + pivot_wider

library(dplyr)
library(tidyr)

result <- df %>%
  distinct(patient_id, drug, headache_cured) %>%
  # 按药物和治愈状态统计人数
  count(drug, headache_cured) %>%
  # 转换为宽格式匹配期望输出
  pivot_wider(
    names_from = headache_cured,
    values_from = n,
    names_prefix = "n_patients_",
    values_fill = 0
  ) %>%
  # 重命名列名
  rename(
    n_patients_cured = `n_patients_TRUE`,
    n_patients_not_cured = `n_patients_FALSE`
  )

print(result)

两种方法都能得到符合要求的输出,去重步骤是关键,确保同一患者同药物只被计数一次。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:55:20