Intermediate

String & Date Handling

Work with text using stringr, categorical data using forcats, and dates using lubridate.

stringr: String Manipulation

stringr provides a consistent set of functions for working with strings. All start with str_:

R
library(stringr)

text <- c("Hello World", "R Programming", "Data Science 101")

# Detect patterns
str_detect(text, "World")      # TRUE FALSE FALSE
str_detect(text, "[0-9]")      # FALSE FALSE TRUE

# Extract matches
str_extract(text, "[A-Z][a-z]+")  # "Hello" "Programming" "Data"
str_extract_all(text[3], "[0-9]+")  # "101"

# Replace
str_replace(text, "World", "R")       # "Hello R" ...
str_replace_all(text, "[aeiou]", "*") # Replace all vowels

# Split
str_split("a,b,c,d", ",")  # list: "a" "b" "c" "d"

# Combine
str_c("Hello", "World", sep = " ")  # "Hello World"

# Other useful functions
str_to_upper("hello")   # "HELLO"
str_to_lower("HELLO")   # "hello"
str_to_title("hello world")  # "Hello World"
str_trim("  spaces  ")   # "spaces"
str_pad("42", 5, pad = "0")  # "00042"
str_length("hello")      # 5

forcats: Working with Factors

R
library(forcats)

sizes <- factor(c("S", "M", "L", "S", "XL", "M", "S", "L"))

# Reorder by frequency
fct_infreq(sizes)

# Reorder by another variable
df <- tibble(size = sizes, value = c(10,20,30,15,40,25,12,35))
fct_reorder(df$size, df$value, .fun = mean)

# Lump rare levels together
fct_lump(sizes, n = 2)  # Keep top 2, rest become "Other"

# Recode levels
fct_recode(sizes,
  "Small" = "S",
  "Medium" = "M",
  "Large" = "L",
  "Extra Large" = "XL"
)

# Reverse order
fct_rev(sizes)

lubridate: Dates and Times

R
library(lubridate)

# Parse dates from strings
ymd("2024-03-15")         # Year-Month-Day
mdy("03/15/2024")         # Month/Day/Year
dmy("15-03-2024")         # Day-Month-Year
ymd_hms("2024-03-15 14:30:00")

# Extract components
d <- ymd("2024-03-15")
year(d)      # 2024
month(d)     # 3
day(d)       # 15
wday(d, label = TRUE)  # Fri
quarter(d)   # 1

# Date arithmetic
d + days(10)       # 2024-03-25
d + months(2)      # 2024-05-15
d + years(1)       # 2025-03-15

# Difference between dates
d2 <- ymd("2024-12-31")
d2 - d               # Time difference of 291 days
as.numeric(d2 - d)   # 291

# Time zones
now()                         # Current date-time
now(tzone = "US/Eastern")    # Specific timezone
with_tz(d, "Europe/London")  # Convert timezone

# Intervals and durations
interval <- d %--% d2
as.period(interval)  # 9m 16d 0H 0M 0S
Pattern: In data analysis pipelines, you often combine these packages: use stringr to clean text columns, lubridate to parse date columns, and forcats to order categorical variables for better plotting with ggplot2.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.