Detect matches

  • str_detect(): returns a logical vector that is TRUE if the pattern matches an element of the character vector and FALSE otherwise:
  • can be used with filter()
str_detect(c("a", "b", "c"), "[aeiou]")
## [1]  TRUE FALSE FALSE
# find all the most popular names containing a lower-case “x”
babynames |> 
  filter(str_detect(name, "x")) |> 
  count(name, wt = n, sort = TRUE)
## # A tibble: 974 × 2
##    name            n
##    <chr>       <int>
##  1 Alexander  665492
##  2 Alexis     399551
##  3 Alex       278705
##  4 Alexandra  232223
##  5 Max        148787
##  6 Alexa      123032
##  7 Maxine     112261
##  8 Alexandria  97679
##  9 Maxwell     90486
## 10 Jaxon       71234
## # ℹ 964 more rows