为什么 filter(str_detect() 使用 R 返回错误的值?

Why is filter(str_detect() returning the wrong values using R?

我正在尝试匹配符合特定工作代码的人,但是有很多缩写(例如,“dr.”和“dir”都是主管。出于某种原因,我的代码产生了明显错误的答案(例如,它在下面的示例中保留了 'kvp coordinator'),我无法弄清楚发生了什么:

library(dplyr)
library(stringr)
test <- tibble(name = c("Corey", "Sibley", "Justin", "Kate", "Ruth", "Phil", "Sara"),
               title = c("kvp coordinator", "manager", "director", "snr dr. of marketing", "drawing expert", "dir of finance", "direct to mail expert"))

test %>%
  filter(str_detect(title, "chief|vp|president|director|dr\.|dir\ |dir\."))

在上面的示例中,应该只剩下 Justin、Kate 和 Phil,但不知何故过滤器并没有删除 Corey。

除了答案,如果你能解释为什么我得到这个奇怪的结果,我将不胜感激。

str_detect 模式中的 vpkvp 匹配,这就是您在输出中得到它的原因。

test %>% filter(str_detect(title, "chief|\bvp\b|president|director|dr\.|dir\ |dir\."))
# A tibble: 3 x 2
  name   title               
  <chr>  <chr>               
1 Justin director            
2 Kate   snr dr. of marketing
3 Phil   dir of finance