Functional Programming, Text and Dates

Article · 3:00

Replacing loops with the purrr map family, taming text with stringr, and the date arithmetic lubridate makes possible.

purrr does what the apply family does, with a consistent interface and - the real advantage - a guaranteed return type. sapply() returns a vector or a list or a matrix depending on what it finds, which means a function that works in testing can return a different shape in production. map() always returns a list. map_dbl() always returns a double vector, or errors. map_chr(), map_int(), map_lgl() likewise. Naming the type you expect turns a silent shape change into an immediate error, which is the whole point.

map2() walks two inputs in parallel, pmap() walks any number, and walk() is for side effects like writing files, returning its input invisibly so it chains.

purrr also has the shorthand \(x) x + 1 (base R's lambda, from 4.1) and the older ~ .x + 1 formula form. Both appear constantly in real code.

stringr replaces base R's string functions with a consistent set: every function starts str_, every one takes the string first, and every one takes the same regular expression engine. That first-argument consistency is what lets them pipe. Base R's grepl(pattern, x) and substr(x, start, stop) put the string in different positions, which is why they do not chain.

Regular expressions are the hard part, not the package. A few that cover most needs: \\d a digit, \\w a word character, \\s whitespace, . anything, + one or more, * zero or more, ^ start, $ end, [abc] any of those, (...) a capture group. Note the double backslash - R's string parser eats one, so the regex engine sees \d when you write \\d.

lubridate makes dates bearable. Base R's as.Date needs a format string you have to get exactly right; ymd(), dmy() and mdy() parse by naming the order of the components and work out the separators themselves. Extraction is year(), month(), day(), wday(). Arithmetic uses periods (months(1) - calendar months, variable length) and durations (dmonths(1) - a fixed number of seconds). The difference matters: adding one calendar month to 31 January is undefined, and %m+% is the operator that handles it by clamping to the month end instead of returning NA.

library(purrr)
library(stringr)
library(lubridate)
library(dplyr)

# ---- purrr: a loop, with a return type you can rely on ---------------
nums <- list(1, 2, 3, 4)

map(nums, \(x) x^2)          # always a LIST
map_dbl(nums, \(x) x^2)      # always a double vector: 1 4 9 16
map_chr(nums, \(x) paste0("n", x))
map_lgl(nums, \(x) x > 2)

# ~ .x is the older shorthand, and is everywhere in existing code:
map_dbl(nums, ~ .x^2)

# Why the typed variants matter. sapply() returns whatever it feels like:
sapply(list(1, 2), \(x) x)        # a numeric vector
sapply(list(1, "a"), \(x) x)      # a character vector
sapply(list(), \(x) x)            # a LIST. Same call, three shapes.
# map_dbl() would have errored on the second and returned double(0) on
# the third. An error you see beats a shape you did not notice.

# Two inputs in step:
map2_dbl(c(1, 2, 3), c(10, 20, 30), \(x, y) x * y)   # 10 40 90

# Side effects, chainably:
walk(c("a.csv", "b.csv"), \(f) message("would write ", f))

# Read and stack every CSV in a folder - the loop this replaces is
# eight lines with a pre-allocated list and an index:
# files <- list.files("data", pattern = "\\.csv$", full.names = TRUE)
# all   <- map_df(files, readr::read_csv)

# ---- stringr: every function takes the string first ------------------
s <- c("Ada Lovelace", "Grace Hopper", "alan turing")

str_length(s)                       # 12 12 11
str_to_upper(s); str_to_title(s)
str_sub(s, 1, 4)                    # "Ada " "Grac" "alan"
str_trim("  padded  ")
str_c("a", "b", sep = "-")          # "a-b"

str_detect(s, "^A")                 # TRUE FALSE FALSE - does it match?
str_subset(s, "o")                  # the elements that match
str_count(s, "a")                   # how many times, per element
str_replace(s,     "a", "@")        # the FIRST match in each
str_replace_all(s, "a", "@")        # every match
str_split(s, " ")                   # a list of character vectors

# Note the DOUBLE backslash: R's parser eats one, so the regex engine
# receives \d when you type \\d.
phones <- c("call 020 7946 0018", "no number here")
str_extract(phones, "\\d{3} \\d{4} \\d{4}")   # the match, or NA

emails <- c("ada@example.com", "not an email")
str_detect(emails, "^[\\w.]+@[\\w.]+\\.\\w+$")   # TRUE FALSE

# Capture groups come back as columns:
str_match("2026-11-23", "(\\d{4})-(\\d{2})-(\\d{2})")
#      [,1]         [,2]   [,3] [,4]
# [1,] "2026-11-23" "2026" "11" "23"

# ---- lubridate: name the ORDER, not the format -----------------------
ymd("2026-11-23"); dmy("23/11/2026"); mdy("Nov 23, 2026")
ymd_hms("2026-11-23 14:30:00", tz = "Europe/London")

d <- ymd("2026-11-23")

year(d); month(d); day(d)
month(d, label = TRUE)         # Nov
wday(d,   label = TRUE)        # Mon
quarter(d); week(d); leap_year(d)

# Periods are calendar time. Durations are a fixed number of seconds.
d + months(1)        # 2026-12-23  - one calendar month
d + dmonths(1)       # a fixed 30.44 days later, so mid-afternoon

# The month-end problem, and its fix:
ymd("2026-01-31") + months(1)        # NA  - there is no 31 February
ymd("2026-01-31") %m+% months(1)     # 2026-02-28 - clamps to month end

# Intervals, for "how long between":
span <- interval(ymd("2026-01-01"), d)
as.period(span)                       # 10m 22d
time_length(span, "days")             # 326

# Rounding, which is how you aggregate by month:
floor_date(d, "month")       # 2026-11-01
# df |> summarise(total = sum(x), .by = floor_date(date, "month"))

Discussion

No questions on this topic yet. Sign in to ask the first one.