Week 7: Strings, Factors & Dates

GPH-GU 2182: Statistical Programming in R · Fall 2026

Yang Feng, PhD

New York University · School of Global Public Health

2026-10-21

Welcome Back! (Week 7)

Today’s Roadmap

  1. Strings I: stringr detection, extraction, replacement.
  2. Strings II: Regular expression building blocks.
  3. Factors: forcats for ordered, lumped categories.
  4. Dates: lubridate parsing and date arithmetic.
  5. AI Corner: Auditing AI-written regex.

Today’s Milestones

  • Homework 7: Released today (strings, factors, dates).
  • 📝 Quiz 3: Last 30 minutes of class (covers Weeks 5–6).

Cycle 1: Working with Strings

Why Text Data Matters in Public Health

Free-text fields are everywhere, and they are messy:

  • Diagnosis descriptions: "Type 2 diabetes mellitus" vs "T2DM" vs "type II diabetes"
  • Medication entries: "metformin 500mg BID", "METFORMIN 500 MG"
  • Site codes: "NYC-BK-014", "nyc-qn-101"
library(stringr)   # every function starts with str_
library(dplyr)
library(tidyr)     # drop_na()
library(r02pro)    # the gm data

stringr gives consistent, pipe-friendly tools: the first argument is always the string vector.

The Core stringr Verbs

meds <- c("metformin 500mg", "Lisinopril 10mg", "atorvastatin 20mg")
Function Question Example Result
str_detect() Does it match? str_detect(meds, "statin") FALSE FALSE TRUE
str_count() How many matches? str_count(meds, "m") 3 1 1
str_extract() What matched? str_extract(meds, "\\d+mg") "500mg" "10mg" "20mg"
str_replace() Swap the match str_replace(meds, "mg", " mg") "metformin 500 mg" "Lisinopril 10 mg" "atorvastatin 20 mg"
  • str_to_lower(), str_to_upper(), str_trim(), str_length() handle cleanup basics.

str_detect() Powers filter()

# gm rows for countries whose name contains "stan"
gm |>
  filter(year == 2008, str_detect(country, "stan")) |>
  select(country, life_expectancy)
# A tibble: 6 × 2
  country      life_expectancy
  <chr>                  <dbl>
1 Afghanistan             59.9
2 Kazakhstan              67.3
3 Pakistan                63.1
4 Tajikistan              68  
5 Turkmenistan            68.8
6 Uzbekistan              66.2

Case-Insensitive Matching

# Normalize case first, then match
gm |>
  filter(str_detect(str_to_lower(country), "united")) |>
  distinct(country)
# A tibble: 3 × 1
  country             
  <chr>               
1 United Arab Emirates
2 United Kingdom      
3 United States       

Pattern matching + last week’s verbs = powerful cohort selection.

👥 Paired Exercise 1: Medication Cleanup (10 min)

Task

Your worksheet defines a messy prescriptions tibble.

  1. Add drug_lower: the drug column in lowercase (str_to_lower).
  2. Filter to rows where drug_lower contains "metformin".
  3. Extract the dose (digits followed by "mg") into a dose column with str_extract().
  4. Count how many prescriptions mention "bid" (twice daily) using str_detect() + sum().

Checklist

  • Normalize case before matching.
  • The regex "\\d+mg" reads: one or more digits, then mg.
  • sum() of a logical counts the TRUEs (Week 2!).

Cycle 2: Regular Expression Building Blocks

Regex: A Pattern Mini-Language

Pattern Matches Example
abc literal text "abc"
. any single character "a.c" matches "abc", "a2c"
\\d any digit "\\d\\d" matches "42"
\\w letter, digit, or _
\\s whitespace
[abc] one of a, b, c "[TF]" matches "T" or "F"
[0-9] character range same as \\d

Tip

In R strings you must double the backslash: the regex \d is typed "\\d".

Quantifiers & Anchors

Pattern Meaning
x? zero or one x
x* zero or more
x+ one or more
x{3} exactly three
^x starts with x
x$ ends with x

Quantifiers & Anchors in Action

codes <- c("NYC-BK-014", "BOS-DT-2", "NYC-QN-101", "nyc-si-77")

str_detect(codes, "^NYC")        # starts with NYC (case-sensitive!)
[1]  TRUE FALSE  TRUE FALSE
str_extract(codes, "\\d+$")      # trailing run of digits
[1] "014" "2"   "101" "77" 
str_detect(codes, "^[A-Z]{3}-")  # three capitals then a dash
[1]  TRUE  TRUE  TRUE FALSE

str_replace() and str_replace_all()

notes <- c("pt reports HTN; hx of htn in family",
           "no HTN noted")

# First match only
str_replace(notes, "HTN", "hypertension")
[1] "pt reports hypertension; hx of htn in family"
[2] "no hypertension noted"                       
# Every match, case-normalized first
notes |>
  str_to_lower() |>
  str_replace_all("htn", "hypertension")
[1] "pt reports hypertension; hx of hypertension in family"
[2] "no hypertension noted"                                
  • Great for expanding abbreviations before analysis.
  • str_remove() / str_remove_all() are shortcuts for replacing with "".

👥 Paired Exercise 2: Parsing Site Codes (10 min)

Task

Using the site_codes vector in your worksheet:

  1. Which codes are valid, i.e. match "^[A-Z]{3}-[A-Z]{2}-\\d+$"? (str_detect)
  2. Extract the numeric site number at the end of each code.
  3. Extract the 2-letter borough segment between the dashes with str_extract() and "-[A-Z]{2}-", then clean the dashes with str_remove_all().
  4. Standardize all codes to uppercase; how many become valid?

Checklist

  • Anchors ^ and $ force a full match.
  • Build regex incrementally: test each piece.
  • Invalid-then-valid after uppercasing shows why we normalize early!

Cycle 3: Factors with forcats

Factors: Categorical Data Done Right

A factor stores a categorical variable with known, fixed levels:

library(forcats)

severity <- factor(c("mild", "severe", "moderate", "mild", "severe"),
                   levels = c("mild", "moderate", "severe"))
levels(severity)
[1] "mild"     "moderate" "severe"  
table(severity)
severity
    mild moderate   severe 
       2        1        2 
  • Levels control ordering in tables, models, and ggplot2 axes.
  • Without explicit levels, R sorts alphabetically: rarely what you want!

fct_reorder(): Order Levels by a Statistic

The #1 factor trick for readable plots: order categories by their value, not alphabetically.

library(ggplot2)

gm |>
  filter(year == 2008) |>
  drop_na(life_expectancy, region) |>
  group_by(region) |>
  summarize(mean_le = mean(life_expectancy)) |>
  ggplot(aes(x = mean_le, y = fct_reorder(region, mean_le))) +
  geom_col(fill = "steelblue") +
  labs(y = NULL, x = "Mean life expectancy (2008)")

Bars now rise in order: instantly readable.

fct_reorder(): Order Levels by a Statistic

fct_lump(): Collapse Rare Categories

Too many categories? Keep the most common, lump the rest into "Other":

gm |>
  filter(year == 2008) |>
  drop_na(region) |>
  mutate(region_top = fct_lump(region, n = 5)) |>
  count(region_top, sort = TRUE)
# A tibble: 6 × 2
  region_top         n
  <fct>          <int>
1 Other            108
2 Western Asia      17
3 Eastern Africa    16
4 Western Africa    16
5 Caribbean         13
6 South America     12
  • Keeps the 5 largest levels plus "Other"; see also fct_infreq() and fct_rev().

👥 Paired Exercise 3: Ordered Regional Charts (10 min)

Task

  1. From gm 2008, compute mean child_mortality per region (drop missing values).
  2. Make a horizontal bar chart without fct_reorder(): note the alphabetical mess.
  3. Remake it with fct_reorder(region, mean_cm).
  4. Use fct_lump(region, n = 6) on the raw rows, then count() the lumped factor.

Checklist

  • fct_reorder(category, value) inside aes().
  • Compare the two charts: which tells the story faster?
  • Lumping keeps dashboards uncluttered.

Cycle 4: Dates with lubridate

Parsing Dates: Match the Order

library(lubridate)

ymd("2026-10-21")        # ISO style
[1] "2026-10-21"
mdy("10/21/2026")        # US style
[1] "2026-10-21"
dmy("21.10.2026")        # European style
[1] "2026-10-21"
visit_dates <- ymd(c("2026-01-15", "2026-03-02", "2026-10-21"))
  • Function name = the order of year, month, day in your raw text.
  • Parsing returns a true Date object: sortable, plottable, subtractable.

Date Components

d <- ymd("2026-10-21")

year(d)
[1] 2026
month(d)
[1] 10
wday(d, label = TRUE)          # day of the week
[1] Wed
Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat

Date Arithmetic

d + days(30)                   # follow-up in 30 days
[1] "2026-11-20"
d - years(1)                   # one year ago
[1] "2025-10-21"
# Elapsed time between events
admit    <- ymd("2026-09-30")
discharge <- ymd("2026-10-21")
as.numeric(discharge - admit)   # length of stay in days
[1] 21

Intervals & Age Computation

dob   <- ymd("1985-06-15")
visit <- ymd("2026-10-21")

# Exact age in years at visit
age <- interval(dob, visit) / years(1)
floor(age)   # completed years
[1] 41

Warning

Never compute age as (visit - dob) / 365.25 for clinical work; leap years and month lengths make interval() / years(1) the reliable idiom.

AI Corner: The Overconfident Regex

Asked to extract doses like "500mg", an AI wrote:

rx <- c("500mg", "500 mg", "dose mg unknown")
str_extract(rx, "[0-9]*mg")
[1] "500mg" "mg"    "mg"   

Audit findings:

  1. * means zero or more: the pattern matches a bare "mg" with no digits at all.
  2. On "500 mg" (space before the unit) it returns just "mg", silently losing the dose.
  3. Nobody tested edge cases.

AI Corner: The Audited Regex

# The audited version: at least one digit, optional space
str_extract(rx, "\\d+ ?mg")
[1] "500mg"  "500 mg" NA      

Important

Regex from AI is a hypothesis, not an answer. Always test on: a normal case, a spaced case, and a should-NOT-match case.

📝 Quiz 3 (Last 30 Minutes)

  • Coverage: Weeks 5–6 (dplyr verbs, pipes, grouped summaries, joins, pivoting).
  • Format: Paper-based, closed-book, no electronic devices.
  • Length: 20 minutes, multiple choice.

Note

Laptops closed, please. Your in-class worksheet should already be pushed to GitHub before the quiz begins.

Wrap-Up & Next Steps

Before We Meet Again

📌 To Do This Week

  • Homework 7 (strings, factors, dates): due date on the course website.
  • Read: R02Pro Ch 12 (control flow & iteration).
  • Push today’s worksheet to GitHub.

🔭 Next Week

  • if / else decisions and vectorized ifelse().
  • for and while loops; accumulator patterns.
  • When not to loop: vectorization first!

Questions? Office hours are listed on the syllabus page, or email anytime.