Learn R · 11/15

String Manipulation with stringr

8 min read

Welcome to the fascinating world of string manipulation in R! You might be wondering, "Why do I need to bother with text?" Well, in the vast universe of data, not everything is numbers. A lot of valuable information is hidden within text, from customer reviews to social media posts. The stringr package is your trusty spaceship to navigate and tame this textual data.

The Problem: Raw text data is often messy, inconsistent, and unstructured. Imagine trying to analyze thousands of product reviews where people write dates in different formats, misspell words, or use inconsistent capitalization. It's like trying to assemble a puzzle with pieces from different boxes.

The Solution: The stringr package, a part of the tidyverse ecosystem, provides a set of consistent and easy-to-use functions to clean, process, and manipulate strings. It's designed to make working with text as painless as possible.

🚀 Getting Started: Installation and Setup

Before we embark on our journey, let's make sure our spaceship is ready. Installing stringr is as simple as a single command. It's often included within the tidyverse package, which is a collection of essential R packages for data science.

r
# The easiest way to get stringr is to install the whole tidyverse:
install.packages("tidyverse")

# Alternatively, install just stringr:
install.packages("stringr")

Once installed, you need to load it into your R session to start using its powerful functions.

r
library(stringr)

Now, let's dive into the core concepts!


🔧 Basic String Operations: Length, Concatenation, and Case

Think of these as the fundamental tools in your string manipulation toolkit. They are the screwdrivers and wrenches you'll reach for most often.

str_length(): How Long is That String?

The Problem: You have a vector of usernames and need to enforce a character limit. How do you check the length of each username?

The Solution: The str_length() function is your go-to for finding the number of characters in a string.

r
# Let's create a vector of strings
usernames <- c("DataWizard", "R_Rocks", "StatisticsSuperstar", "123Go")

# Get the length of each username
str_length(usernames)

Explanation:
str_length() takes a character vector as input and returns a numeric vector containing the length of each corresponding string. It's straightforward and incredibly useful for data validation and cleaning.

str_c(): Sticking Strings Together

The Problem: You have separate columns for first names and last names and need to create a full name column.

The Solution: str_c() is the "super glue" for strings. It allows you to combine multiple strings into one.

r
first_names <- c("Grace", "Ada", "Marie")
last_names <- c("Hopper", "Lovelace", "Curie")

# Combine first and last names with a space in between
full_names <- str_c(first_names, " ", last_names)
print(full_names)

# You can also collapse a vector of strings into a single string
interests <- c("coding", "data visualization", "machine learning")
str_c(interests, collapse = ", ")

Explanation:
The first argument to str_c() is the initial vector of strings. Subsequent arguments are what you want to paste onto them. The sep argument specifies the separator to be used between the concatenated strings (by default, it's an empty string). The collapse argument is used to combine the elements of a vector into a single string.

str_to_lower(), str_to_upper(), str_to_title(): A Matter of Case

The Problem: You're analyzing survey responses, but people have entered their city names with inconsistent capitalization (e.g., "New York", "new york", "NEW YORK"). To treat them as the same city, you need to standardize the case.

The Solution: stringr provides a trio of functions to handle case conversion effortlessly.

r
cities <- c("New York", "london", "TOKYO")

# Convert to lowercase
str_to_lower(cities)

# Convert to uppercase
str_to_upper(cities)

# Convert to title case
str_to_title("a tale of two cities")

Explanation:
These functions are self-explanatory and are workhorses in data cleaning. Consistent casing is crucial for accurate grouping and analysis of categorical text data.


🧩 Introduction to Regular Expressions (Regex) in R

Don't be scared by the name! Regular expressions, or "regex" for short, are simply a powerful way to describe patterns in text. Think of them as a mini-language for searching and manipulating strings.

The Problem: You need to find all the email addresses in a block of text, but they can have different usernames, domains, and top-level domains. A simple search for "email" won't work.

The Solution: Regex allows you to define a pattern that matches the structure of an email address (e.g., [email protected]).

In R, you write regular expressions as strings. stringr functions that work with patterns interpret these strings as regular expressions.

Here are a few fundamental building blocks of regex that you'll use frequently:

Metacharacter Description
. Matches any single character (except a newline)
\\d Matches any digit (0-9)
\\s Matches any whitespace character (space, tab, etc.)
[abc] Matches any one character from the set a, b, or c
[^abc] Matches any character not in the set a, b, or c
^ Matches the start of the string
$ Matches the end of the string
* Matches the preceding element zero or more times
+ Matches the preceding element one or more times
? Matches the preceding element zero or one time
{n} Matches the preceding element exactly n times
{n,} Matches the preceding element n or more times
{n,m} Matches the preceding element between n and m times

A Funny Exaggeration: Learning regex is like gaining a superpower. Suddenly, you can see the hidden patterns in text that were invisible before. You'll start wanting to use it everywhere, even to find your lost keys (though it's not quite that powerful... yet!).


🔍 Pattern Matching: Detecting and Extracting Substrings

Now that we have a basic understanding of regex, let's see how stringr helps us use these patterns to find what we're looking for.

str_detect(): Is the Pattern There?

The Problem: You have a list of product descriptions and want to flag all the ones that mention a specific feature, say "waterproof".

The Solution: str_detect() returns a logical vector indicating whether a pattern is present in each string.

r
descriptions <- c("A durable, waterproof phone case.", "Stylish and lightweight.", "Our most waterproof backpack yet!")

# Detect which descriptions contain "waterproof"
str_detect(descriptions, "waterproof")

Explanation:
str_detect() is perfect for filtering your data based on the presence or absence of certain keywords or patterns.

str_extract() & str_extract_all(): Pulling Out the Good Stuff

The Problem: You have a long string of text containing multiple phone numbers, and you need to pull them all out.

The Solution: str_extract() will retrieve the first match of a pattern, while str_extract_all() will get all of them.

r
text <- "Contact us at 555-1234 or for emergencies, call 911-555-7890."

# Let's define a regex for a phone number (e.g., 3 digits, a hyphen, and 4 digits)
phone_pattern <- "\\d{3}-\\d{4}"

# Extract the first phone number
str_extract(text, phone_pattern)

# Extract all phone numbers
str_extract_all(text, phone_pattern)

Explanation:
str_extract() is great when you know there's only one piece of information you need to grab. str_extract_all() is your tool when you need to capture every instance of a pattern. The output of str_extract_all() is a list, as each string in your input vector could have a different number of matches.


🛠️ String Modification: Replacing and Removing Patterns

Finding patterns is great, but what if you want to change them? stringr has you covered.

str_replace() & str_replace_all(): Find and Replace

The Problem: You have a dataset with inconsistent date formats (e.g., "2024-02-21", "02/21/2024") and you want to standardize them to "YYYY-MM-DD".

The Solution: str_replace() and str_replace_all() allow you to substitute matched patterns with a new string. str_replace() will only replace the first occurrence, while str_replace_all() will replace every instance.

r
dates <- c("Recorded on 2024/02/21", "Next meeting is 2024/03/15")

# Replace the first slash with a hyphen
str_replace(dates, "/", "-")

# Replace all slashes with hyphens
str_replace_all(dates, "/", "-")

A Real-World Scenario: Imagine you're a data journalist cleaning up a scraped dataset of news headlines. You might use str_replace_all() to correct common misspellings or to standardize company names (e.g., replacing "Goggle" and "Goog" with "Google").

str_remove() & str_remove_all(): Making Things Disappear

The Problem: Your data contains unwanted characters, like currency symbols or HTML tags, that you need to get rid of before performing numerical analysis.

The Solution: str_remove() and str_remove_all() are the "delete" keys for your strings.

r
prices <- c("$50.00", "Price: $75.50", "On sale for $25")

# Remove the first dollar sign
str_remove(prices, "\\$")

# Remove all non-numeric characters (except the decimal point)
# This is a more advanced regex, but very powerful!
cleaned_prices <- str_remove_all(prices, "[^\\d\\.]")
print(cleaned_prices)

Under the Hood: It's good to know that stringr is built on top of the stringi package, which in turn uses the ICU (International Components for Unicode) C library. This means that stringr's functions are not only user-friendly but also highly efficient and performant, even on large datasets.


This guide has covered the most frequently used functions in stringr that you'll encounter in your data science journey. By mastering these, you'll be well-equipped to handle the majority of string manipulation tasks that come your way. Happy coding! 💻

📚 Further Reading and References

Challenge

You are given a character vector reviews containing raw product feedback. Your task is to use functions from the stringr package to clean this data and extract key information into a new, structured vector.

Complete the following steps:

  1. First, remove all HTML-like tags (e.g., <p>, </p>) from the reviews vector. A tag is any sequence of characters enclosed by < and >.
  2. Next, working with the result from step 1, correct all occurrences of the common misspelling 'teh' to 'the'.
  3. From the corrected strings, extract the Product ID from each review. A Product ID is defined as a single capital letter, followed by a hyphen, and then four digits (e.g., A-1122).
  4. Similarly, extract the star rating from the corrected strings. The rating is the single digit that immediately precedes the word 'star' or 'stars'.
  5. Finally, create a new character vector called report. Each element of report must be a single string that combines the extracted ID and rating, formatted exactly as: "ID: [Product ID] | Rating: [Star Rating]".

Assign your final formatted vector to the variable report.

Expected result

Your script should produce a character vector named report.

This vector must contain four elements, where each element corresponds to an original review and is formatted precisely as specified.

The final report vector should contain the following values:

r
c("ID: A-1122 | Rating: 5", "ID: B-3344 | Rating: 3", "ID: A-5566 | Rating: 5", "ID: C-7788 | Rating: 1")
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.