Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท Strings, Dates and Regular Expressions

stringr and lubridate: Tidy Text and Date Handling in R

Use stringr and lubridate from the tidyverse: str_detect, str_replace_all, str_extract, ymd, dmy, periods versus durations, floor_date, time zones and month-end rules.

Base R can do everything in the previous three lessons, but its function names and argument orders are inconsistent (grepl(pattern, x) but substr(x, start, stop); gsub(pattern, replacement, x)). Two tidyverse packages smooth over that:

  • stringr wraps string functions in a consistent family: every function starts with str_, takes the string first and the pattern second, and handles NA predictably.
  • lubridate parses and manipulates dates and times with function names that read like the format (ymd(), dmy(), hms()).

Install them once with install.packages(c("stringr", "lubridate")) (or install.packages("tidyverse")) and load them with library(). Both are used heavily inside dplyr pipelines. If regular expressions are new to you, read Regular Expressions in R first, since stringr uses the same pattern language (the ICU flavor, which is very close).

R is not available on this site, so the R code below is read-only and we show output only where we are certain of it. A Python block at the end compares month arithmetic.

stringr: the basics

R
library(stringr)

x <- c("apple", "banana", "cherry")
str_length(x)                          # 5 6 6
str_to_upper("hello")                  # "HELLO"
str_to_title("hello world")            # "Hello World"
str_sub("abcdef", 2, 4)                # "bcd"
str_sub("abcdef", -3)                  # "def"   (negative counts from the end)
str_pad("7", width = 3, pad = "0")     # "007"
str_trunc("abcdefghij", width = 6)     # "abc..."
str_squish("  too    many   spaces ")  # "too many spaces"
str_c("a", "b", sep = "-")             # "a-b"
str_flatten(c("a", "b", "c"), ", ")    # "a, b, c"

str_squish() trims both ends and collapses inner runs of whitespace; it is usually what you want instead of trimws(). str_c() is paste0() with NA propagation: if any input is NA, the output is NA.

Detecting, counting and locating

R
fruit <- c("apple", "banana", "cherry", "date")

str_detect(fruit, "an")           # FALSE TRUE FALSE FALSE
str_count("banana", "a")          # 3
str_starts(fruit, "b")            # FALSE TRUE FALSE FALSE
fruit[str_detect(fruit, "e$")]    # "apple" "date"

str_detect() returns a logical vector, which is perfect inside dplyr::filter(): filter(df, str_detect(name, "^A")). Compare with base R's grepl("^A", name): the same job, but the stringr argument order matches the rest of the pipe.

Replacing and extracting

R
str_replace("banana", "a", "A")        # "bAnana"      (first match)
str_replace_all("banana", "a", "A")    # "bAnAnA"      (all matches)
str_replace_all("a1b22", "\\d", "#")   # "a#b##"

str_extract("order #4821 shipped", "\\d+")       # "4821"
str_extract_all("a1b22c333", "\\d+")             # a list: "1" "22" "333"
str_extract_all("a1b22c333", "\\d+", simplify = TRUE)   # a one-row matrix

str_replace_all() can also take a named vector to run several replacements in one pass: str_replace_all(x, c("cat" = "dog", "red" = "blue")). It supports back-references as \\1 in the replacement.

To pull out the pieces of a structured string, use groups with str_match():

R
str_match("2026-03-15", "(\\d+)-(\\d+)-(\\d+)")
# a matrix: column 1 is the whole match, then one column per group:
# "2026-03-15" "2026" "03" "15"

Splitting and interpolating

R
str_split("a,b,c", ",")                  # a list holding "a" "b" "c"
str_split_fixed("a-b-c", "-", n = 2)     # a matrix: "a" and "b-c"
name <- "Ada"; n <- 3
str_glue("Hello {name}, you have {n + 1} messages")   # Hello Ada, you have 4 messages

str_glue() evaluates the R expression inside { }, which makes report text much easier to read than a chain of paste0() calls.

Base R and stringr side by side

Task Base R stringr
Length nchar(x) str_length(x)
Test for pattern grepl(p, x) str_detect(x, p)
Replace first sub(p, r, x) str_replace(x, p, r)
Replace all gsub(p, r, x) str_replace_all(x, p, r)
Extract matches regmatches(x, gregexpr(p, x)) str_extract_all(x, p)
Substring substr(x, a, b) str_sub(x, a, b)
Trim trimws(x) str_trim(x) / str_squish(x)

lubridate: parsing dates

Name the function after the order of the parts in your text and lubridate figures out the separators:

R
library(lubridate)

ymd("2026-03-15")                  # "2026-03-15"
ymd("20260315")                    # "2026-03-15"
dmy("15/03/2026")                  # "2026-03-15"
mdy("March 15, 2026")              # "2026-03-15"
ymd_hms("2026-03-15 14:30:00")     # "2026-03-15 14:30:00 UTC"

The result is an ordinary Date or POSIXct, so everything from Dates and Times in R still applies. Strings that cannot be parsed give NA and a warning telling you how many failed.

Extracting and changing components

R
d <- ymd("2026-03-15")
year(d)       # 2026
month(d)      # 3
day(d)        # 15
wday(d)       # 1   (Sunday = 1 by default)
yday(d)       # 74  (1-based day of year)
leap_year(2028)   # TRUE

Every accessor can also be assigned to: year(d) <- 2030 changes the year in place. month(d, label = TRUE) returns the month name as an ordered factor, which sorts and plots in calendar order.

Rounding dates

floor_date(), ceiling_date() and round_date() snap a date to a unit. They are the cleanest way to group by month or week:

R
floor_date(d, "month")                  # "2026-03-01"
ceiling_date(d, "month")                # "2026-04-01"
floor_date(d, "week")                   # "2026-03-15"   (weeks start on Sunday)
floor_date(d, "week", week_start = 1)   # "2026-03-09"   (weeks start on Monday)

A monthly summary then reads naturally:

R
library(dplyr)
sales |>
  mutate(month = floor_date(day, "month")) |>
  group_by(month) |>
  summarise(total = sum(amount))

Periods versus durations

This is the most important idea in lubridate. Time spans come in two kinds:

  • A period is a calendar unit: days(1), months(1), years(1). "One month" is as long as the calendar says.
  • A duration is an exact number of seconds, created with a d prefix: ddays(1) is always 86,400 seconds; dhours(2) is 7,200 seconds.
R
d + days(10)                       # "2026-03-25"
d + months(1)                      # "2026-04-15"
as.numeric(ddays(1))               # 86400
as.numeric(dhours(2))              # 7200

Use periods for "same time next month" and durations for "exactly 24 hours later". The two differ across daylight-saving changes and leap years, which is when mixing them causes real bugs.

The month-end rule

Adding a month to January 31 has no valid answer, because February 31 does not exist. + months(1) returns NA in that case. The %m+% operator rolls the date back to the last valid day instead:

R
ymd("2026-01-31") + months(1)      # NA
ymd("2026-01-31") %m+% months(1)   # "2026-02-28"

Intervals, ages and time zones

R
span <- interval(ymd("2026-03-15"), ymd("2026-12-25"))
span / days(1)                                 # 285
interval(ymd("1990-06-20"), ymd("2026-03-15")) %/% years(1)   # 35 (completed years)

t <- ymd_hms("2026-03-15 14:30:00")            # UTC by default
with_tz(t, "Asia/Tokyo")                       # "2026-03-15 23:30:00 JST"  same instant
force_tz(t, "Asia/Tokyo")                      # "2026-03-15 14:30:00 JST"  same clock, new instant

with_tz() keeps the moment and changes how it is shown; force_tz() keeps the clock reading and changes the moment. Pick the first for display, the second only to repair a time that was stamped with the wrong zone.

Compare with Python

Here is a Python stand-in for the month-end rule and the floor_date()/age calculations, so you can run the logic.

Python Python comparison: month-end, floor_date and age

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Using the wrong parser order: ymd("15/03/2026") is not a valid year-month-day. Use dmy().
  • Reaching for months(1) with end-of-month dates and getting NA. Use %m+%.
  • Mixing periods and durations, e.g. dyears(1) when you mean "same date next year".
  • Forgetting that stringr takes the string first (str_detect(x, p)), the reverse of grepl(p, x).
  • Loading both packages and not noticing masking messages. lubridate::year() and similar names are best written with :: in shared code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which stringr function replaces all matches of a pattern?

    str_replace() changes only the first match in each string. str_replace_all() changes every match.
  2. 2. Which lubridate call parses "15/03/2026"?

    The function name lists the order of the parts: day, month, year.
  3. 3. What is the difference between months(1) and a duration such as ddays(30)?

    Periods follow the calendar and vary in length; durations are exact numbers of seconds.
  4. 4. What does ymd('2026-01-31') %m+% months(1) return?

    %m+% rolls back to the last valid day of the target month, so the result is February 28.
  5. 5. What does with_tz() change?

    with_tz() keeps the instant and shows it in another time zone. force_tz() changes the instant by keeping the clock reading.

Summary

  • stringr gives every string job a consistent str_*(string, pattern) function; str_glue() interpolates variables.
  • lubridate parses dates by naming the order of the parts: ymd(), dmy(), ymd_hms().
  • Use accessors such as year(), month(), wday() and rounding with floor_date() for grouping.
  • Periods follow the calendar, durations count seconds; %m+% handles month ends.
  • with_tz() changes the display zone; force_tz() changes the instant.

Next: Base R Graphics