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

在R中检测每个patient_id是否存在多个不同hla-b27值

标记存在多个不同hla-b27值的patient_id

首先准备模拟数据:

df <- data.frame(
  hla_b27 = c(1.3, 3.4, 3.4, 2.6, 2.6, 2.6, 6.3, 6.3, 6.3),
  patient_id = c("01", "01", "01", "02", "02", "02", "06", "06", "06")
)

方法一:Base R实现

通过分组聚合计算每个patient_id对应的唯一hla-b27值数量,再判断是否大于1并转为1/0标记:

result_base <- aggregate(hla_b27 ~ patient_id, data = df, function(x) as.integer(length(unique(x)) > 1))
colnames(result_base)[2] <- "multiple_hla_b27"

# 输出结果
result_base

输出结果:

patient_idmultiple_hla_b27
011
020
060

方法二:tidyverse(dplyr)实现

用管道流完成分组、统计唯一值数量、生成标记的操作,代码更简洁直观:

library(dplyr)

result_tidy <- df %>%
  group_by(patient_id) %>%
  summarise(multiple_hla_b27 = as.integer(n_distinct(hla_b27) > 1)) %>%
  ungroup()

# 输出结果
result_tidy

输出结果与Base R方法一致。

关键逻辑说明

  • length(unique(x))/n_distinct(x):统计每个patient_id组内不同hla-b27值的数量
  • as.integer(...):将逻辑判断(是否大于1)转换为1(是)或0(否)的标记值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:05:07