Taming Text Data (stringr)
7 min read
Welcome to the wild west of Data Science: Text Data.
If numerical data is a well-organized Excel spreadsheet, text data is a toddler who just found a permanent marker and a white wall. It is messy, unpredictable, and usually requires a lot of scrubbing.
In the Tidyverse, our scrub brush is the stringr package. It is designed to make string manipulation consistent, simple, and easier to use than Base R's sometimes confusing string functions.
Fun Fact:
stringris actually a wrapper around a faster, more powerful C library calledstringi. Think ofstringias the heavy-duty industrial chemical andstringras the spray bottle mixed to the perfect ratio for daily cleaning.
0. Boilerplate & Setup 🛠️
Before we start slicing strings, let's ensure you have the tools. stringr is part of the core Tidyverse, so if you have installed tidyverse, you are ready.
Installation:
install.packages("tidyverse")Loading:
library(tidyverse)
# or specifically: library(stringr)1. Introduction to Regular Expressions (Regex) in R 🧩
Definition
A Regular Expression (Regex) is a sequence of characters that specifies a search pattern. It is a language within a language used to find specific character combinations in strings.
The Problem
Imagine you need to find every row in a dataset that contains a phone number.
- One user typed: "555-0199"
- Another typed: "(555) 0199"
- Another typed: "555.0199"
If you search for exact text, you fail. You need a pattern that says: "Three digits, maybe a separator, three digits..."
The Solution: Regex Syntax
Regex allows us to describe the structure of the text we want.
In R, Regex can be tricky because \ (backslash) is used as an escape character in strings and in Regex. Rule of thumb: If you see a Regex tutorial online that uses one backslash \d, in R you usually need two \\d.
Essential Patterns for Industry:
| Pattern | Meaning | Example Match |
|---|---|---|
. |
Any character (except newline) | a.c matches "abc", "a@c" |
\\d |
Any digit | Order_\\d matches "Order_5" |
\\w |
Any word character (letters/numbers) | user_\\w matches "user_a", "user_1" |
\\s |
Whitespace (space, tab, newline) | Hello\\sWorld matches "Hello World" |
^ |
Start of the string | ^A matches "Apple" but not "Banana" |
$ |
End of the string | s$ matches "Cats" but not "Soup" |
* |
0 or more times | go*d matches "gd", "god", "good" |
+ |
1 or more times | go+d matches "god", "good" (not "gd") |
[abc] |
One of these specific characters | [Bb]anana matches "Banana" or "banana" |
⚠️ The "Escape" Trap
If you want to find a literal period . (which usually means "any character"), you must escape it.
In R: "\\." looks for a literal dot.
2. Detecting Patterns: str_detect() and str_count() 🕵️♀️
The Problem
You have a dataset of customer feedback. You want to filter for only those rows where the customer mentioned "urgent" or "error".
The Solution
str_detect() returns a logical vector (TRUE or FALSE). It asks: "Is this pattern present inside this string?"
str_detect()
This is best paired with filter() from dplyr.
feedback <- c("Great service", "Urgent error found", "Error 404", "Happy customer")
# Detect strings containing "error" (case sensitive by default)
str_detect(feedback, "error")
# Output: [1] FALSE TRUE FALSE FALSE
# Notice "Error 404" is FALSE because of the capital E.
# Industry Standard: Make it case insensitive or use regex class
str_detect(feedback, regex("error", ignore_case = TRUE))
# Output: [1] FALSE TRUE TRUE FALSEstr_count()
Sometimes you don't just want to know if it's there, but how many times.
logs <- c("Error: 404, Error: 500", "Status: OK", "Error: 403")
# How many errors per log?
str_count(logs, "Error")
# Output: [1] 2 0 1Pro Tip: Because
TRUEequals 1 andFALSEequals 0 in R, you can usesum(str_detect(data, pattern))to quickly count how many rows match your pattern!
3. Extracting and Replacing: str_extract() and str_replace() ✂️
The Problem
You scraped product data, but the price column looks like this: "$12.99 USD", "€50.00". You can't do math on that. You need just the numbers. Or, you need to redact sensitive info like "User: [Name]" to "User: REDACTED".
The Solution
- Extract: Pull the matching piece out.
- Replace: Swap the matching piece with something else.
str_extract()
Extracts the first match found in the string.
prices <- c("$12.99", "Price: $5.00", "€20")
# Regex explanation: \\d+ means "one or more digits", \\. means "a dot", * means "maybe"
# This regex looks for a number, optionally followed by decimals
str_extract(prices, "\\d+\\.?\\d*")
# Output: [1] "12.99" "5.00" "20"Note: If you need ALL matches in a single string (e.g., extracting multiple hashtags), use str_extract_all().
str_replace() and str_replace_all()
str_replace() swaps the first match. str_replace_all() swaps every match.
text <- "The color is red. Red is bright."
# Replace the first instance (Case sensitive)
str_replace(text, "red", "blue")
# Output: "The color is blue. Red is bright."
# Replace all instances (ignoring case)
str_replace_all(text, regex("red", ignore_case = TRUE), "blue")
# Output: "The color is blue. blue is bright."Industry Use Case - Cleaning Whitespace:
Removing specific annoyances, like removing "ID-" from "ID-402".
ids <- c("ID-101", "ID-202")
str_replace(ids, "ID-", "")
# Output: "101" "202"4. String Manipulation: Length, Padding, and Case 📏
The Problem
Data entry is messy.
- Users leave spaces:
" John "vs"John". - Capitalization varies:
"USA","usa","Usa". - IDs are inconsistent:
"1"vs"001".
The Solution
Standardization functions.
Case Transformation
Always lower-case your text data before doing analysis (word clouds, joins) to avoid mismatches.
raw_data <- c("Apple", "apple", "APPLE")
str_to_lower(raw_data) # "apple" "apple" "apple"
str_to_upper(raw_data) # "APPLE" "APPLE" "APPLE"
str_to_title(raw_data) # "Apple" "Apple" "Apple"Handling Whitespace (str_trim vs str_squish)
Whitespace is the silent killer of data joins.
str_trim(): Removes spaces from Start and End.str_squish(): Removes spaces from Start and End AND reduces repeated internal spaces to a single space. (Highly Recommended)
messy <- " Data Science is cool "
str_trim(messy)
# Output: "Data Science is cool" (Internal spaces remain)
str_squish(messy)
# Output: "Data Science is cool" (Perfect!)Length and Padding
str_length() counts characters. str_pad() adds characters to ensure fixed width (common in SKU codes or Zip codes).
codes <- c("1", "25", "450")
# Pad with zeros on the left until width is 3
str_pad(codes, width = 3, side = "left", pad = "0")
# Output: "001" "025" "450"🏗️ Real World Example: The "Dirty" Dataframe
Let's clean a realistic messy dataframe.
library(tidyverse)
# Imagine this data from a web form
df <- tibble(
id = c("1", " 2", "3"),
email = c("[email protected]", "jane.doe@gmail", "[email protected] "),
phone = c("555-0101", "555.0102", "(555) 0103")
)
# The Cleanup Pipeline
clean_df <- df %>%
mutate(
# 1. Pad IDs to be "001", "002"
id_clean = str_pad(str_squish(id), width = 3, pad = "0"),
# 2. Fix email: remove spaces, lowercase
email_clean = str_to_lower(str_squish(email)),
# 3. Detect valid gmail accounts
is_gmail = str_detect(email_clean, "gmail\\.com"),
# 4. Standardize phone: Remove all non-digits
phone_digits = str_replace_all(phone, "\\D", "") # \\D means "Not a digit"
)
print(clean_df)Result: You now have consistent IDs, matchable emails, and pure numerical phone numbers ready for database storage.
📚 References & Further Reading
- Official stringr Documentation: stringr.tidyverse.org
- R for Data Science (String Chapter): r4ds.had.co.nz/strings
- Regex Cheat Sheet: RStudio Cheat Sheets
Final Thought: Regex looks scary like hieroglyphics at first. But once you know just 4 or 5 patterns (
\d,\w,^,$), you can solve 90% of text problems. Don't memorize it all; just memorize where to look it up! Happy cleaning! 🧹
Challenge
You have received a raw data extract of customer information that needs to be cleaned and standardized before being loaded into the main database. The data is provided in an R tibble named raw_customer_data.
Perform the following data cleaning operations using the stringr package and assign the resulting tibble to a new variable called cleaned_data.
customer_idcolumn: The IDs are inconsistent. Standardize them by padding each ID with leading zeros (0) so that every ID is exactly 5 characters long.email_addresscolumn: Normalize the email addresses. This requires removing all leading and trailing whitespace, converting all characters to lowercase, and collapsing any internal consecutive whitespace into a single space.phone_contactcolumn: Transform the phone contact information into a standardized, digit-only format. Remove all non-digit characters (e.g., parentheses, hyphens, spaces, letters) from each string.Create a new column
is_corporate: Add a new logical column to the tibble. This column should beTRUEif the original, uncleanedemail_addressstring ends with either.comor.org, andFALSEotherwise. This check must be case-insensitive.
Expected result
Your code should produce a single tibble named cleaned_data. The tibble must have 4 rows and 4 columns: customer_id, email_address, phone_contact, and the newly created is_corporate.
The columns should contain the data cleaned and transformed according to the challenge instructions. The final tibble's structure and content should look exactly like this:
# A tibble: 4 × 4
customer_id email_address phone_contact is_corporate
<chr> <chr> <chr> <lgl>
1 00034 [email protected] 1234567890 TRUE
2 01024 [email protected] 9876543210 TRUE
3 00089 [email protected] 5551234567 FALSE
4 00512 [email protected] 1112223333 TRUE