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

R语言:为DataFrame新增Coinfection列标记合并感染状态

为DataFrame添加感染合并标记列

需求说明

在包含42列的DataFrame中新增一列Coinfection:

  • 若某一行中Detected的出现次数≥2,标记为Coinfection
  • 若仅1次或全为Not Detected,标记为Negative

示例数据构造

ID<- c(1,2,3,4,5)
CV<- c("Detected", "Not Detected", "Detected", "Not Detected", "Detected")
RV<- c("Not Detected", "Detected", "Not Detected", "Detected", "Not Detected")
BP<- c("Detected", "Detected", "Not Detected", "Detected", "Detected")
df <- data.frame(ID, CV, RV, BP)

解法1:Base R 实现

直接用rowSums统计每行Detected的数量,再通过ifelse完成标记:

# 排除ID列,统计其余列中"Detected"的出现次数
df$Coinfection <- ifelse(rowSums(df[-1] == "Detected") >= 2, "Coinfection", "Negative")

解法2:dplyr 实现(tidyverse风格)

适合习惯tidyverse语法的用户,按行统计后完成标记:

library(dplyr)

df <- df %>%
  rowwise() %>%
  # 统计除ID外所有列中"Detected"的次数
  mutate(detected_num = sum(c_across(-ID) == "Detected")) %>%
  # 根据次数设置标记
  mutate(Coinfection = case_when(
    detected_num >= 2 ~ "Coinfection",
    TRUE ~ "Negative"
  )) %>%
  ungroup() %>%
  select(-detected_num) # 可选:移除中间计数列

验证结果

执行上述代码后,打印df即可得到期望的结果:

ID           CV           RV           BP Coinfection
1  1      Detected Not Detected      Detected Coinfection
2  2 Not Detected      Detected      Detected Coinfection
3  3      Detected Not Detected Not Detected    Negative
4  4 Not Detected      Detected      Detected Coinfection
5  5      Detected Not Detected      Detected Coinfection

内容的提问来源于stack exchange,提问作者T.McMillen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:25:37