Skip to Content
Course content

19: Working with Strings via stringr

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this happen to almost every R developer I've mentored. You're cleaning a dataset, you need to filter some strings, and you reach for base R's grep(). It feels straightforward until you realize you've spent the last twenty minutes fighting with the return types.

# The goal: Get a list of logs that are "Critical" or "Error"
logs <- c("INFO: System start", "ERROR: Disk full", "DEBUG: Heartbeat", "CRITICAL: CPU Overheat")

# I want the actual strings, so I do this:
critical_logs <- grep("CRITICAL|ERROR", logs)

print(critical_logs)
# [1] 2 4
# Wait... why did I get numbers instead of the text?

The index vs. logical confusion

The problem here is that base R's string functions are inconsistent. grep() returns the indices of the matches. If you wanted the actual strings, you'd have to wrap that in a subsetting bracket: logs[grep(...)]. But then you realize grepl() (with an 'l') exists, which returns a logical vector (TRUE/FALSE). It's a constant mental tax: "Do I need the index, the logical, or the string itself?"

This is exactly why I stopped using base R for string manipulation and switched to stringr. It's a wrapper around the ICU library, but more importantly, it's designed for humans. Every function starts with str_, and the arguments are always in the same order: the string you're searching comes first, and the pattern comes second.

library(stringr)

# Now, if I want the actual strings, I use str_subset
critical_logs <- str_subset(logs, "CRITICAL|ERROR")
print(critical_logs)
# [1] "ERROR: Disk full" "CRITICAL: CPU Overheat"

# If I want a TRUE/FALSE vector for filtering a dataframe, I use str_detect
is_critical <- str_detect(logs, "CRITICAL|ERROR")
# [1] FALSE  TRUE FALSE  TRUE

Trimming the fat and swapping text

Real-world data is almost always filthy. You'll often find trailing spaces or inconsistent prefixes that make your joins fail. In base R, you'd be juggling gsub() and trimws(). In stringr, we have a much more intuitive pipeline.

Take a look at this messy vector of product IDs. They have random whitespace and a "PROD_" prefix we don't need:

ids <- c(" PROD_123 ", "PROD_456  ", "  PROD_789")

# First, let's get rid of that annoying surrounding whitespace
ids <- str_trim(ids)

# Now, let's remove the prefix. 
# Note: str_replace only does the first match; str_replace_all does every instance.
clean_ids <- str_remove(ids, "PROD_")

print(clean_ids)
# [1] "123" "456" "789"

Extracting specific patterns

Sometimes you don't want to remove text; you want to pull a specific piece out of a larger string. This is where str_extract() becomes your best friend. Instead of trying to figure out regexpr() and regmatches() (which are, frankly, a nightmare to type), you just tell stringr what you're looking for.

Imagine you have a column of emails and you just need the domain names. You can use a simple regular expression to grab everything after the @ symbol:

emails <- c("alice@gmail.com", "bob@yahoo.com", "charlie@outlook.com")

# Extract everything from the '@' to the end of the string
domains <- str_extract(emails, "@.*$")

print(domains)
# [1] "@gmail.com" "@yahoo.com" "@outlook.com"

I should mention: stringr is part of the tidyverse, so it plays incredibly well with dplyr. You can drop str_detect or str_replace directly into a filter() or mutate() call, and it just works. No more weird index-subsetting gymnastics.




📋 Practical Task

Standardizing Messy Inventory SKUs

You have been handed a vector of SKU codes from a legacy warehouse system. They are incredibly inconsistent: some have leading/trailing spaces, some are uppercase, some are lowercase, and some have an annoying "SKU-" prefix that needs to be removed for the new database.

Your task: Use the stringr package to clean the following vector: raw_skus <- c(" SKU-101a ", "sku-202B", " SKU-303C ", "sku-404d ")

The final result should be a vector where:

  • All leading and trailing whitespace is removed.
  • The "SKU-" or "sku-" prefix is gone.
  • All characters are converted to uppercase.

Write the code to transform raw_skus into the cleaned version: c("101A", "202B", "303C", "404D").

Rating
0 0

There are no comments for now.

to be the first to leave a comment.