library(tidyverse)── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.2.1 ✔ readr 2.2.0
✔ forcats 1.0.1 ✔ stringr 1.6.0
✔ ggplot2 4.0.3 ✔ tibble 3.3.1
✔ lubridate 1.9.5 ✔ tidyr 1.3.2
✔ purrr 1.2.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(stringr)
library(lubridate)
# Movie ratings dataset
ratings <- tibble(
person = c(
"Alice", "Alice", "Alice", "Alice", "Alice",
"Brian", "Brian", "Brian", "Brian", "Brian"
),
movie = c(
"Spider-Man: Brand New Day",
"The Odyssey",
"Toy Story 5",
"The Super Mario Galaxy Movie",
"Project Hail Mary",
"Spider-Man: Brand New Day",
"The Odyssey",
"Toy Story 5",
"The Super Mario Galaxy Movie",
"Project Hail Mary"
),
rating = c(
5, 4, 4, 5, 4,
4, 5, 3, 4, 5
)
)
# ------------------------------
# Work with dates
# ------------------------------
ratings <- ratings %>%
mutate(
rating_date = seq.Date(
from = as.Date("2026-09-01"),
by = "day",
length.out = n()
),
year = year(rating_date),
month = month(rating_date, label = TRUE),
day = day(rating_date),
weekday = wday(rating_date, label = TRUE)
)
# ------------------------------
# Work with strings
# ------------------------------
ratings <- ratings %>%
mutate(
person_upper = str_to_upper(person),
movie_upper = str_to_upper(movie),
title_length = str_length(movie),
movie_clean = str_squish(movie)
)
# ------------------------------
# Use regular expressions
# ------------------------------
ratings <- ratings %>%
mutate(
# Detect a number
contains_number =
str_detect(movie, "\\d"),
# Extract a number
movie_number =
str_extract(movie, "\\d+"),
# Detect movies beginning with "The"
starts_with_the =
str_detect(movie, "^The"),
# Detect movies ending with "Movie"
ends_with_movie =
str_detect(movie, "Movie$")
)
# View results
ratings# A tibble: 10 × 16
person movie rating rating_date year month day weekday person_upper
<chr> <chr> <dbl> <date> <dbl> <ord> <int> <ord> <chr>
1 Alice Spider-Man:… 5 2026-09-01 2026 Sep 1 Tue ALICE
2 Alice The Odyssey 4 2026-09-02 2026 Sep 2 Wed ALICE
3 Alice Toy Story 5 4 2026-09-03 2026 Sep 3 Thu ALICE
4 Alice The Super M… 5 2026-09-04 2026 Sep 4 Fri ALICE
5 Alice Project Hai… 4 2026-09-05 2026 Sep 5 Sat ALICE
6 Brian Spider-Man:… 4 2026-09-06 2026 Sep 6 Sun BRIAN
7 Brian The Odyssey 5 2026-09-07 2026 Sep 7 Mon BRIAN
8 Brian Toy Story 5 3 2026-09-08 2026 Sep 8 Tue BRIAN
9 Brian The Super M… 4 2026-09-09 2026 Sep 9 Wed BRIAN
10 Brian Project Hai… 5 2026-09-10 2026 Sep 10 Thu BRIAN
# ℹ 7 more variables: movie_upper <chr>, title_length <int>, movie_clean <chr>,
# contains_number <lgl>, movie_number <chr>, starts_with_the <lgl>,
# ends_with_movie <lgl>