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
相关产品推荐
相关产品推荐

