Import your data

library(readr)

pixar_films <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/main/data/2025/2025-03-11/pixar_films.csv")
## Rows: 27 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (2): film, film_rating
## dbl  (2): number, run_time
## date (1): release_date
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Chapter 14

Tools

Detect matches

pixar_films %>%
  summarise(n_ending_vowel = sum(str_detect(film, "[aeiou]$"), na.rm = TRUE))
## # A tibble: 1 × 1
##   n_ending_vowel
##            <int>
## 1              6
str_detect(pixar_films$film, "[aeiou]$")
##  [1] FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE
## [13]  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE
## [25] FALSE FALSE    NA
sum(str_detect(pixar_films$film, "[aeiou]$"), na.rm = TRUE)
## [1] 6
mean(str_detect(pixar_films$film, "[aeiou]$"), na.rm = TRUE)
## [1] 0.2307692

Extract matches

# Match titles ending with a vowel (or use any alternation pattern)
vowel_endings <- c("a", "e", "i", "o", "u")
ending_match <- str_c(vowel_endings, "$", collapse = "|")
ending_match
## [1] "a$|e$|i$|o$|u$"
# Extract strings from pixar_films$film that match
has_ending <- str_subset(pixar_films$film, ending_match)
str_extract(has_ending, ending_match)
## [1] "e" "o" "e" "e" "o" "a"

Replacing matches

pixar_films %>%
  mutate(
    film_rev_one = film %>% str_replace("[aeiou]", "-"),
    film_rev_all = film %>% str_replace_all("[aeiou]", "-")
  )
## # A tibble: 27 × 7
##    number film       release_date run_time film_rating film_rev_one film_rev_all
##     <dbl> <chr>      <date>          <dbl> <chr>       <chr>        <chr>       
##  1      1 Toy Story  1995-11-22         81 G           T-y Story    T-y St-ry   
##  2      2 A Bug's L… 1998-11-25         95 G           A B-g's Life A B-g's L-f-
##  3      3 Toy Story… 1999-11-24         92 G           T-y Story 2  T-y St-ry 2 
##  4      4 Monsters,… 2001-11-02         92 G           M-nsters, I… M-nst-rs, I…
##  5      5 Finding N… 2003-05-30        100 G           F-nding Nemo F-nd-ng N-m-
##  6      6 The Incre… 2004-11-05        115 PG          Th- Incredi… Th- Incr-d-…
##  7      7 Cars       2006-06-09        117 G           C-rs         C-rs        
##  8      8 Ratatouil… 2007-06-29        111 G           R-tatouille  R-t-t---ll- 
##  9      9 WALL-E     2008-06-27         98 G           WALL-E       WALL-E      
## 10     10 Up         2009-05-29         96 PG          Up           Up          
## # ℹ 17 more rows