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

使用dplyr过滤数据:移除包含指定值的整组行

使用dplyr移除包含指定值的整组行

我来帮你搞定这个过滤需求!你的核心要求是:按name列分组后,如果某个分组里的SampleType列存在"Blank"值,就把这个分组的所有行都删掉,只保留完全没有"Blank"的分组。

先把你提供的示例数据用代码形式列出来(方便复现):

df <- data.frame(
  fullname = c("step6-a-s", "step7-c-s", "step4-c-s", "Blank2-s", "step6-b-s", "step7-b-s", "step3-c-s", "Blank1-s", "step8-a-s",
               "step7-b-s", "step4-c-s", "Blank2-s", "step6-b-s", "step5-c-s", "Blank1-s", "step2-b-s",
               "step4-a-s", "step1-b-s", "step5-a-s", "step3-a-s", "step4-b-s",
               "step5-c-s", "step3-c-s", "step2-b-s", "step7-c-s", "Blank2-s", "step1-c-s",
               "step4-b-s", "step4-a-s", "step3-b-s", "step1-b-s"),
  name = c("CE 10:0", "CE 10:0", "CE 10:0", "CE 10:0", "CE 10:0", "CE 10:0", "CE 10:0", "CE 10:0", "CE 10:0",
           "CE 10:1", "CE 10:1", "CE 10:1", "CE 10:1", "CE 10:1", "CE 10:1", "CE 10:1",
           "CE 10:3", "CE 10:3", "CE 10:3", "CE 10:3", "CE 10:3",
           "CE 11:0", "CE 11:0", "CE 11:0", "CE 11:0", "CE 11:0", "CE 11:0",
           "CE 11:1", "CE 11:1", "CE 11:1", "CE 11:1"),
  intensity = c(11997.1, 8752, 6969.9, 2231.1, 3275.6, 4485.4, 4191.6, 4349, 8838,
                6155.3, 5899.9, 3098.6, 2945.2, 1207.2, 4173, 3219.4,
                3658.2, 4070, 2776.4, 4821.6, 4145.9,
                7056, 6367.5, 6426.9, 5133.9, 4006.3, 3791.7,
                5183.7, 3549.5, 2822.9, 2495.7),
  SampleType = c("step", "step", "step", "Blank", "step", "step", "step", "Blank", "step",
                 "step", "step", "Blank", "step", "step", "Blank", "step",
                 "step", "step", "step", "step", "step",
                 "step", "step", "step", "step", "Blank", "step",
                 "step", "step", "step", "step")
)

接下来是核心的dplyr代码,逻辑清晰易懂:

library(dplyr)

# 执行过滤操作
filtered_df <- df %>%
  # 按name列分组
  group_by(name) %>%
  # 过滤掉所有包含"Blank"的分组:!any(...) 表示该分组中没有任何一行的SampleType是Blank
  filter(!any(SampleType == "Blank")) %>%
  # 取消分组(可选,但推荐,避免后续操作受分组影响)
  ungroup()

逻辑拆解:

  • group_by(name):将数据按name字段划分为独立分组;
  • !any(SampleType == "Blank"):any()检测分组内是否存在SampleType为"Blank"的行,!取反后,仅保留无"Blank"的分组;
  • ungroup():取消分组标记,恢复数据框的常规状态,避免后续操作受分组限制。

运行这段代码后,结果里会只保留CE 10:3和CE 11:1这两个分组的所有行,完全符合你的需求!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 21:07:44