在Stringr匹配(str_detect)上进行过滤,但R中的特定相似值除外?

在Stringr匹配(str_detect)上进行过滤,但R中的特定相似值除外?,r,dplyr,stringr,R,Dplyr,Stringr,我正在尝试创建一个dplyr管道来进行过滤 设想一个数据框,其中我想从标题列中筛选出最高级的职位: titles Chief Executive Officer Chief Financial Officer Chief Technical Officer Manager Product Manager Programmer Scientist Marketer Lawyer Secretary 过滤它们的R代码(直到“经理”)将是 jobs %>% filter(!str_dete

我正在尝试创建一个dplyr管道来进行过滤

设想一个数据框,其中我想从
标题
列中筛选出最高级的职位:

titles

Chief Executive Officer
Chief Financial Officer
Chief Technical Officer
Manager
Product Manager
Programmer
Scientist
Marketer
Lawyer
Secretary
过滤它们的R代码(直到“经理”)将是

jobs %>% 
filter(!str_detect(title, 'Chief')) %>%
filter(!str_detect(title, 'Manager')) ...
但我仍然希望在最终筛选中保留“程序管理器”,以生成包含所有“低级作业”的新数据帧,如

除了一个特定的字符串外,有没有办法对给定的值指定str_detect()过滤器


假设数据框的列有1000个角色,包括“经理”在内的各种字符串组合,但对于特定的异常总是有一个筛选器。

或者您可以为“产品经理”单独设置一个
筛选器


也可以使用
grepl/grep

jobs[c(grep("Product Manager",jobs$title), 
       grep("Chief|Manager", jobs$title, invert = TRUE)),, drop = FALSE]

为什么不简单地像这样使用锚来“管理器”
…%>%过滤器(!stringr::str_detect(title,“^Chief”^^Manager$)
^
锚告诉正则表达式匹配以“Manager”开头的字符串。另一个锚确保字符串也必须以“Manager”结尾。
library(tidyverse)

jobs %>% 
filter((!str_detect(title, "Chief|Manager")) | str_detect(title, "Product Manager"))


#            title
#1 Product Manager
#2      Programmer
#3       Scientist
#4        Marketer
#5          Lawyer
#6       Secretary
jobs[c(grep("Product Manager",jobs$title), 
       grep("Chief|Manager", jobs$title, invert = TRUE)),, drop = FALSE]