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

如何无循环筛选仅在B队列有值的抗原(AG)?

筛选符合条件的抗原列解决方案

核心需求

从testdat数据框中筛选出仅在B队列有非NA值,A、C、D队列全为NA的抗原(AG)列,同时保留前5列患者基础信息,无需循环实现。


dplyr 实现方案

使用dplyr的select()结合where()函数,直接对列进行条件判断:

library(dplyr)

# 筛选目标列
selected_ags <- testdat %>%
  select(
    # 保留前5列基础信息
    Patient:Age,
    # 对AG列应用筛选逻辑
    where(function(col) {
      # 条件1:A/C/D队列中该列所有值均为NA
      all(is.na(col[testdat$Cohort %in% c("A", "C", "D")])) &&
      # 条件2:B队列中该列至少存在一个非NA值
      any(!is.na(col[testdat$Cohort == "B"]))
    })
  )

Base R 实现方案

如果不习惯使用dplyr,可以用Base R的sapply()遍历列进行判断:

# 提取所有AG列的列名
ag_col_names <- colnames(testdat)[6:ncol(testdat)]

# 判断每列是否符合筛选条件
keep_cols <- sapply(ag_col_names, function(col) {
  all(is.na(testdat[testdat$Cohort %in% c("A", "C", "D"), col])) &&
  any(!is.na(testdat[testdat$Cohort == "B", col]))
})

# 生成筛选后的数据集
selected_ags_base <- testdat[, c(colnames(testdat)[1:5], ag_col_names[keep_cols])]

常见问题说明

之前使用group_by()+filter()出错,是因为这两个函数是对行进行分组筛选,而我们的需求是对列做条件判断,因此需要用select()(dplyr)或列遍历方法(Base R)来实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:52:07