Exploring Netflix with lubridate, stringr & regex

Week 14

Published

December 2, 2026

The data

The Netflix Movies and TV Shows dataset on Kaggle lists the movies and TV shows on Netflix, one row per title. Almost every interesting column is stored as text, even the ones that are really dates, numbers or lists. That makes it a perfect dataset for practicing:

  • lubridate, to turn text like "September 25, 2021" into real dates;
  • stringr, to detect, extract, split and count pieces of text;
  • regular expressions (regex), the pattern language that stringr’s pattern arguments use.
library(tidyverse) # includes stringr and lubridate

Download netflix_titles.csv from Kaggle or Thompson’s data/ folder and save it in a data/ folder next to this file. If the file isn’t there, this code reads an older copy of the same data from TidyTuesday instead, so the page still renders.

path <- "../data/netflix_titles.csv"
#if (!file.exists(path)) {
#  path <- "https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-04-20/netflix_titles.csv"
# }


# or download from Thompson's data/ folder:
if (!file.exists(path)) {
  path <- "https://euclid.nmu.edu/~joshthom/dat309/data/netflix_titles.csv"
}

netflix <- read_csv(path)
glimpse(netflix)
Rows: 7,787
Columns: 12
$ show_id      <chr> "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s1…
$ type         <chr> "TV Show", "Movie", "Movie", "Movie", "Movie", "TV Show",…
$ title        <chr> "3%", "7:19", "23:59", "9", "21", "46", "122", "187", "70…
$ director     <chr> NA, "Jorge Michel Grau", "Gilbert Chan", "Shane Acker", "…
$ cast         <chr> "João Miguel, Bianca Comparato, Michel Gomes, Rodolfo Val…
$ country      <chr> "Brazil", "Mexico", "Singapore", "United States", "United…
$ date_added   <chr> "August 14, 2020", "December 23, 2016", "December 20, 201…
$ release_year <dbl> 2020, 2016, 2011, 2009, 2008, 2016, 2019, 1997, 2019, 200…
$ rating       <chr> "TV-MA", "TV-MA", "R", "PG-13", "PG-13", "TV-MA", "TV-MA"…
$ duration     <chr> "4 Seasons", "93 min", "78 min", "80 min", "123 min", "1 …
$ listed_in    <chr> "International TV Shows, TV Dramas, TV Sci-Fi & Fantasy",…
$ description  <chr> "In a future where the elite inhabit an island paradise f…

Look at the types: date_added and duration are <chr> (text), and listed_in (the genres), cast and country pack several values into one string, separated by commas.

Cleaning the text columns

date_added: text to dates with lubridate

lubridate’s parsing functions are named after the order of the parts in the text: mdy() reads month-day-year, ymd() reads year-month-day, dmy() reads day-month-year, and so on. They understand month names, so "September 25, 2021" needs no extra help.

mdy("September 25, 2021")
[1] "2021-09-25"

Once a column is a date, lubridate can pull out its parts: year(), month(), day() and wday() (day of the week). label = TRUE gives names (Sep, Fri) instead of numbers.

netflix <- netflix |>
  mutate(
    date_added = mdy(str_trim(date_added)), # str_trim() removes stray spaces first
    year_added = year(date_added),
    month_added = month(date_added, label = TRUE),
    weekday_added = wday(date_added, label = TRUE)
  )

netflix |> select(title, date_added, year_added, month_added, weekday_added) |> head()
# A tibble: 6 × 5
  title date_added year_added month_added weekday_added
  <chr> <date>          <dbl> <ord>       <ord>        
1 3%    2020-08-14       2020 Aug         Fri          
2 7:19  2016-12-23       2016 Dec         Fri          
3 23:59 2018-12-20       2018 Dec         Thu          
4 9     2017-11-16       2017 Nov         Thu          
5 21    2020-01-01       2020 Jan         Wed          
6 46    2017-07-01       2017 Jul         Sat          

A few titles have no date_added, so they become NA:

netflix |> count(is.na(date_added))
# A tibble: 2 × 2
  `is.na(date_added)`     n
  <lgl>               <int>
1 FALSE                7777
2 TRUE                   10

duration: one column, two kinds of numbers

duration holds minutes for movies ("93 min") but seasons for TV shows ("4 Seasons", "1 Season"):

netflix |> count(type, duration, sort = TRUE) |> slice_head(n = 3, by = type)
# A tibble: 6 × 3
  type    duration      n
  <chr>   <chr>     <int>
1 TV Show 1 Season   1608
2 TV Show 2 Seasons   382
3 TV Show 3 Seasons   184
4 Movie   90 min      136
5 Movie   93 min      131
6 Movie   91 min      125

We split it into two numeric columns with regex:

  • "\\d+" means one or more digits: \\d is any digit and + means “one or more of the previous thing”. str_extract() returns the first match, "93", which as.integer() turns into a number.
  • "min$" means min at the end of the string ($ anchors the pattern to the end).
  • "Seasons?$" matches Season or Seasons: ? makes the s optional.
netflix <- netflix |>
  mutate(
    minutes = if_else(str_detect(duration, "min$"),
                      as.integer(str_extract(duration, "\\d+")), NA),
    seasons = if_else(str_detect(duration, "Seasons?$"),
                      as.integer(str_extract(duration, "\\d+")), NA)
  )

netflix |> select(type, duration, minutes, seasons) |> head()
# A tibble: 6 × 4
  type    duration  minutes seasons
  <chr>   <chr>       <int>   <int>
1 TV Show 4 Seasons      NA       4
2 Movie   93 min         93      NA
3 Movie   78 min         78      NA
4 Movie   80 min         80      NA
5 Movie   123 min       123      NA
6 TV Show 1 Season       NA       1

Question 1: When did Netflix add its titles?

year_added tells us the year each title arrived. Counting by year and type shows the growth of Netflix’s library, and the shift between movies and TV.

netflix |>
  filter(!is.na(year_added)) |>
  count(year_added, type) |>
  ggplot(aes(year_added, n, fill = type)) +
  geom_col() +
  labs(title = "Titles added to Netflix each year",
       x = NULL, y = "Titles added", fill = NULL)

The library exploded from 2016 on, the year Netflix launched in most of the world. (The last year in the data is partial: the dataset was collected partway through it.)

Question 2: What day and month does Netflix add new titles?

netflix |>
  filter(!is.na(weekday_added)) |>
  count(weekday_added) |>
  ggplot(aes(weekday_added, n)) +
  geom_col() +
  labs(title = "Titles added by day of the week", x = NULL, y = "Titles added")

Friday stands out: new releases arrive in time for the weekend.

day() gives the day of the month. Is the 1st of the month special?

netflix |>
  filter(!is.na(date_added)) |>
  count(day_of_month = day(date_added)) |>
  ggplot(aes(day_of_month, n)) +
  geom_col() +
  labs(title = "Titles added by day of the month",
       x = "Day of the month", y = "Titles added")

The 1st of the month dwarfs every other day. That’s when licensing deals typically start, so whole batches of older movies arrive at once.

Question 3: Are Christmas movies added in time for Christmas?

str_detect() finds titles that mention Christmas. Wrapping the pattern in regex(..., ignore_case = TRUE) matches Christmas, CHRISTMAS and christmas alike.

christmas <- netflix |>
  filter(str_detect(title, regex("christmas", ignore_case = TRUE)))

christmas |> select(title, date_added) |> head()
# A tibble: 6 × 2
  title                  date_added
  <chr>                  <date>    
1 48 Christmas Wishes    2017-12-20
2 5 Star Christmas       2018-12-07
3 A Bad Moms Christmas   2020-02-14
4 A California Christmas 2020-12-14
5 A Christmas Catch      2020-11-04
6 A Christmas Prince     2017-11-17
christmas |>
  filter(!is.na(month_added)) |>
  count(month_added, .drop = FALSE) |> # .drop = FALSE keeps months with 0 titles
  ggplot(aes(month_added, n)) +
  geom_col() +
  labs(title = "When are Christmas titles added?", x = NULL, y = "Titles added")

The large majority arrive in November and December, just in time.

Question 4: How old is a title when it reaches Netflix?

release_year is when the title first came out; year_added is when it reached Netflix. The difference is its age on arrival.

netflix |>
  filter(!is.na(year_added)) |>
  mutate(age_when_added = year_added - release_year) |>
  group_by(type) |>
  summarize(
    median_age = median(age_when_added),
    share_new = mean(age_when_added <= 1) # added within a year of release
  )
# A tibble: 2 × 3
  type    median_age share_new
  <chr>        <dbl>     <dbl>
1 Movie            1     0.503
2 TV Show          0     0.675

TV shows usually arrive the same year they’re released (a median age of 0), and about two-thirds arrive within a year. Movies are a little older (a median of 1 year), and only half arrive within a year: the rest are older films licensed for the catalog.

Question 5: How long are Netflix movies? How many seasons do shows last?

With minutes and seasons now numbers, these are ordinary summaries.

netflix |>
  filter(type == "Movie", !is.na(minutes)) |>
  ggplot(aes(minutes)) +
  geom_histogram(binwidth = 5) +
  labs(title = "Movie lengths", x = "Minutes", y = "Movies")

Most movies run between about 85 and 115 minutes, with a median of about 98, plus a long tail of short films and specials.

netflix |>
  filter(type == "TV Show", !is.na(seasons)) |>
  count(seasons) |>
  mutate(share = n / sum(n))
# A tibble: 15 × 3
   seasons     n    share
     <int> <int>    <dbl>
 1       1  1608 0.667   
 2       2   382 0.159   
 3       3   184 0.0763  
 4       4    87 0.0361  
 5       5    58 0.0241  
 6       6    30 0.0124  
 7       7    19 0.00788 
 8       8    18 0.00747 
 9       9     8 0.00332 
10      10     6 0.00249 
11      11     3 0.00124 
12      12     2 0.000830
13      13     2 0.000830
14      15     2 0.000830
15      16     1 0.000415

Most TV shows on Netflix have only one season.

Question 6: What are the most common genres?

listed_in packs several genres into one string, like "Dramas, International Movies". separate_longer_delim() splits it at each ", " and gives every genre its own row, so we can count them.

genres <- netflix |>
  separate_longer_delim(listed_in, delim = ", ") |>
  rename(genre = listed_in)

genres |>
  count(genre, sort = TRUE) |>
  slice_head(n = 15) |>
  ggplot(aes(n, fct_reorder(genre, n))) +
  geom_col() +
  labs(title = "Most common genres", x = "Titles", y = NULL)

Netflix lists movie and TV genres separately (“Dramas” vs. “TV Dramas”). str_remove() with the pattern "^TV " (^ anchors to the start of the string) combines them:

genres |>
  mutate(genre = str_remove(genre, "^TV ")) |>
  count(genre, sort = TRUE) |>
  slice_head(n = 5)
# A tibble: 5 × 2
  genre                      n
  <chr>                  <int>
1 Dramas                  2810
2 International Movies    2437
3 Comedies                1996
4 International TV Shows  1199
5 Action & Adventure       871

Question 7: Which countries make the most Netflix titles?

country can list several countries ("United States, India"). The pattern "^[^,]+" extracts the first one:

  • ^ anchors to the start of the string;
  • [^,] means any character that is not a comma (inside brackets, ^ means “not”);
  • + means one or more of them.

So it matches everything up to the first comma.

netflix |>
  filter(!is.na(country)) |>
  mutate(main_country = str_extract(country, "^[^,]+")) |>
  count(main_country, sort = TRUE) |>
  slice_head(n = 10)
# A tibble: 10 × 2
   main_country       n
   <chr>          <int>
 1 United States   2883
 2 India            956
 3 United Kingdom   577
 4 Canada           259
 5 Japan            237
 6 France           196
 7 South Korea      194
 8 Spain            168
 9 Mexico           123
10 Australia        108

Question 8: What are the descriptions about?

The description column is a one-sentence summary of each title. str_count() counts matches, and \\b marks a word boundary, so "\\blove\\b" matches the word love but not glove or lovely.

themes <- c(
  love = "\\blove\\b",
  murder = "\\bmurder",
  family = "\\bfamil(y|ies)\\b",
  friends = "\\bfriends?\\b",
  "true story" = "\\btrue story\\b",
  documentary = "\\bdocumentary\\b"
)

tibble(theme = names(themes), pattern = themes) |>
  mutate(
    titles = map_int(pattern, \(p) sum(str_detect(netflix$description, regex(p, ignore_case = TRUE))))
  ) |>
  arrange(desc(titles))
# A tibble: 6 × 3
  theme       pattern              titles
  <chr>       <chr>                 <int>
1 family      "\\bfamil(y|ies)\\b"    615
2 friends     "\\bfriends?\\b"        543
3 love        "\\blove\\b"            437
4 documentary "\\bdocumentary\\b"     327
5 murder      "\\bmurder"             260
6 true story  "\\btrue story\\b"       48

The patterns use a few more regex tools:

  • \\bmurder (no closing \\b) matches murder, murders and murderer.
  • famil(y|ies) uses alternation: | means “or”, and the parentheses group the choices, so it matches family or families.

Sequels and numbered titles

Can regex find sequels? A first try: titles that end with a space and a number. "\\s\\d+$" means a space (\\s), then one or more digits, at the end of the title.

netflix |>
  filter(str_detect(title, "\\s\\d+$")) |>
  select(title, release_year) |>
  slice_head(n = 10)
# A tibble: 10 × 2
   title                        release_year
   <chr>                               <dbl>
 1 ​Goli Soda 2                          2018
 2 #FriendButMarried 2                  2020
 3 #Selfie 69                           2016
 4 21 Sarfarosh: Saragarhi 1897         2018
 5 5 to 7                               2014
 6 Aadu 2                               2017
 7 ABCD 2                               2015
 8 After Porn Ends 3                    2018
 9 Apollo 18                            2011
10 Arisan 2                             2011

This finds real sequels, like ABCD 2, but also titles that just end in a number, like Apollo 18 and 5 to 7. A regex matches a pattern, not a meaning. We can tighten it: sequels usually end in a single digit from 2 to 9 ([2-9] is a character range), or say Part or Vol. (\\. is a literal period, because a plain . means any character).

sequels <- netflix |>
  filter(str_detect(title, "\\s[2-9]$|Part [0-9IVX]+|Vol\\. \\d"))

sequels |>
  select(title, release_year) |>
  slice_head(n = 10)
# A tibble: 10 × 2
   title                   release_year
   <chr>                          <dbl>
 1 ​Goli Soda 2                     2018
 2 #FriendButMarried 2             2020
 3 5 to 7                          2014
 4 Aadu 2                          2017
 5 ABCD 2                          2015
 6 After Porn Ends 3               2018
 7 Arisan 2                        2011
 8 Asu Mare 2                      2015
 9 Atlas Shrugged: Part II         2012
10 B.A. Pass 2                     2017
nrow(sequels)
[1] 121

Still not perfect, but much closer. Checking a pattern’s matches by eye, and refining it, is a normal part of working with regex.

Regex used in these notes

pattern meaning used for
\\d+ one or more digits numbers in duration
min$ min at the end of the string spotting movies
Seasons?$ Season or Seasons at the end spotting TV shows
^TV TV at the start of the string merging TV and movie genres
^[^,]+ everything up to the first comma the first country
\\blove\\b the whole word love themes in descriptions
famil(y\|ies) family or families alternation with \|
\\s\\d+$ a space and a number at the end numbered titles
[2-9] one digit from 2 to 9 likely sequels
Vol\\. \\d Vol. and a digit, with a literal period volumes

Try it yourself

  1. Which directors have the most titles on Netflix? (Hint: director, like country, can list several people.)
  2. How many titles were added in each season of the year (winter, spring, …)? Use month() and case_when().
  3. Find all titles with a colon in them, like Star Wars: The Clone Wars. What comes before the colon most often? (str_extract(title, "^[^:]+"))
  4. Which rating (TV-MA, PG-13, …) is most common for movies, and for TV shows? Has the mix changed over the years?