首页 > 解决方案 > 过滤/子集包含某些字符串以外的任何内容的行

问题描述

我有包含字符串的列的数据框,并且想要过滤掉所有包含除某些字符串以外的任何内容的行

考虑下面的简化示例:

string <- c('AA', 'BB' , 'AA, BB' , 'BB, AA', 'AAS', 'BB, CC',  'DD', 'A','A, BB', 'BBAA', 'AA,BB')
df <- data.frame(string)

而且我只想维护那些不包含除'AA'和/或以外的任何内容的字符串'BB'

AA
BB
AA, BB
BB, AA
BBAA
AA,BB

请注意,这是一个简化的示例,您不能简单地过滤 AAS、CC 和 DD 或 AA 和 BB 的组合,因为还有更多替代字符串选项。

标签: rfilterdplyr

解决方案


df %>% dplyr::filter(stringr::str_detect(string, "C|D|S", negate=T))
  string

或者

pattern=c('C', 'D', 'S')
df %>% 
    dplyr::filter(
        stringr::str_detect(string, paste(pattern, collapse="|"), negate=T)
)
1     AA
2     BB
3 AA, BB
4 BB, AA

推荐阅读