01 / 20

Cleaning Text Data
in R

Learn how to trim whitespace, replace patterns, and transform messy strings into clean, analysis-ready data using R's built-in text functions.

R Programming

Why Clean Text Matters

Real-world data is messy. Surveys, web scraping, and file imports often produce strings with extra spaces, inconsistent capitalization, and unwanted characters. If you don't clean this data first, your analysis will produce wrong results.

What Is Text Cleaning?

Trimming
Removing leading, trailing, or excess internal whitespace from strings.
Replacing
Swapping out unwanted characters or patterns with correct or empty values.
Transforming
Changing case (upper, lower, title) to make text consistent across records.

The Text Cleaning Pipeline

Raw Input " hello World! " trimws() "hello World!" tolower() "hello world!" gsub() "hello world" Clean Output "hello world" Key Functions: trimws() : Remove whitespace tolower() / toupper() : Change case sub() / gsub() : Replace patterns

Core Functions for Text Cleaning

trimws(x)
Trims leading and trailing whitespace. Use which parameter for "left", "right", or "both" (default).
sub(pattern, replacement, x)
Replaces the first match of a pattern in each string element.
gsub(pattern, replacement, x)
Replaces all matches of a pattern in each string element. The "g" stands for global.
tolower(x) / toupper(x)
Converts all characters to lowercase or uppercase for consistent comparisons.

trimws() : Removing Whitespace

# Trimming whitespace from strings messy <- " Hello World " trimws(messy) # "Hello World" trimws(messy, "left") # "Hello World " trimws(messy, "right") # " Hello World"

sub() vs gsub(): Key Distinction

text <- "banana" sub("a", "@", text) # "b@nana" (first match only) gsub("a", "@", text) # "b@n@n@" (all matches)
sub() gsub()
Matches replaced First only All
"g" prefix means N/A Global
Common use Fix one prefix/suffix Clean entire string

Simple Pattern Matching

The pattern argument in sub() and gsub() can be plain text or a regular expression. For beginners, here are the most useful patterns:

1
"\\s+" : matches one or more whitespace characters (spaces, tabs, newlines).
2
"[^a-zA-Z0-9 ]" : matches any character that is not a letter, digit, or space.
3
"\\d+" : matches one or more digits (0-9). Useful for stripping numbers.
4
"^" and "$" : anchor the match to the start or end of the string.

Step-by-Step Cleaning Workflow

1
Inspect: Use head() and str() to look at your data. Spot spaces, odd characters, and case issues.
2
Trim: Apply trimws() to remove leading and trailing whitespace from all text columns.
3
Standardize case: Use tolower() or toupper() so "NYC", "nyc", and "Nyc" all match.
4
Replace patterns: Use gsub() to remove or replace special characters, collapse multiple spaces, etc.
5
Verify: Check results with unique() and table() to confirm your cleaning worked.

Example 1: Basic Cleanup

# Raw survey data cities <- c(" New York", "new york ", " NEW YORK") # Step 1: Trim whitespace cities <- trimws(cities) # "New York", "new york", "NEW YORK" # Step 2: Standardize to lowercase cities <- tolower(cities) # "new york", "new york", "new york"

Example 2: Removing Special Characters

# Phone numbers with mixed formats phones <- c("(555) 123-4567", "555.123.4567", "555 123 4567") # Remove everything that is NOT a digit clean_phones <- gsub("[^0-9]", "", phones) # "5551234567", "5551234567", "5551234567"

Example 3: Collapsing Internal Spaces

# Names with extra internal spaces names <- c("John Doe", "Jane Smith") # Step 1: Collapse multiple spaces into one names <- gsub("\\s+", " ", names) # "John Doe", "Jane Smith" # Step 2: Trim any remaining edge spaces names <- trimws(names) # "John Doe", "Jane Smith"

Putting It All Together

# Messy product data products <- c(" Widget #1!!", "widget #1", "WIDGET#1 ") # Full cleaning pipeline products <- trimws(products) products <- tolower(products) # Replace special characters with a space products <- gsub("[^a-z0-9]", " ", products) # Collapse multiple spaces into one products <- gsub("\\s+", " ", products) # Trim again to remove any spaces added at the edges products <- trimws(products) # Result: "widget 1", "widget 1", "widget 1"

Common Mistakes to Avoid

✕ Using sub() instead of gsub()
sub() only replaces the first match. If your string has multiple occurrences, you must use gsub() for global replacement.
✕ Forgetting double backslashes
In R, regex special characters need \\ (e.g., "\\s" not "\s"). Single backslash causes errors or silent failures.
✕ Not reassigning the result
trimws(x) returns a new string: it does not modify x in place. You must write x <- trimws(x) to save the change.

Function Reference Table

Function Purpose Example
trimws() Remove edge whitespace trimws(" hi ") → "hi"
sub() Replace first match sub("a","@","banana") → "b@nana"
gsub() Replace all matches gsub("a","@","banana") → "b@n@n@"
tolower() Convert to lowercase tolower("Hi") → "hi"
toupper() Convert to uppercase toupper("Hi") → "HI"
nchar() Count characters nchar("hello") → 5

Question 1 of 5

What does trimws(" R rocks ") return?

Question 2 of 5

Which function replaces all occurrences of a pattern in a string?

Question 3 of 5

What is the output of gsub("[^0-9]", "", "(555) 123-4567")?

Question 4 of 5

You run sub("a", "@", "abracadabra"). What do you get?

Question 5 of 5

Which sequence correctly cleans the string " Hello WORLD " into "hello world"?