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.
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?
The Text Cleaning Pipeline
Core Functions for Text Cleaning
trimws() : Removing Whitespace
sub() vs gsub(): Key Distinction
| 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:
Step-by-Step Cleaning Workflow
Example 1: Basic Cleanup
Example 2: Removing Special Characters
Example 3: Collapsing Internal Spaces
Putting It All Together
Common Mistakes to Avoid
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"?