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

R语言实现分组筛选:某location有一行满足y条件则保留其所有行

方案1:dplyr 分组筛选(最推荐,多条件扩展极方便)

核心逻辑是按location分组后,用any()判断组内是否存在符合条件的行,满足就保留整组所有行:

library(dplyr)

# 单条件示例:保留存在y=6的location所有行
test %>%
  group_by(location) %>%
  filter(any(y == 6)) %>%
  ungroup() # 不需要后续分组操作的话建议加上,避免影响后续逻辑

运行结果和你给出的示例完全一致:

location     x     y
  <chr>    <int> <dbl>
1 here         1     6
2 there        2     7
3 here         3     8
4 there        4     6

多条件筛选直接在filter里加判断即可,比如要筛选同时满足「存在y=6」且「存在x>3」的location所有行:

test %>%
  group_by(location) %>%
  filter(any(y == 6), any(x > 3)) %>%
  ungroup()

如果是或逻辑的多条件,直接写在同一个any()里即可:

# 保留存在y=6 或者 x=5的location所有行
test %>%
  group_by(location) %>%
  filter(any(y == 6 | x == 5)) %>%
  ungroup()

方案2:非分组的匹配方案

如果不想用分组,可以先提取符合条件的location值,再用%in%匹配筛选:

# 单条件示例
test %>%
  filter(location %in% unique(location[y == 6]))

# 多条件示例:存在y=6且x>3的location
test %>%
  filter(location %in% unique(location[y == 6 & x > 3]))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:36:05