R - Strings
R - Modern String Manipulation
Section titled “R - Modern String Manipulation”Working with text data is a common task in any programming language. In R, a string is a piece of text created using either single (') or double (") quotes. While base R has functions for string manipulation, the modern, recommended approach is to use the stringr package, which is part of the tidyverse. stringr provides a more consistent, intuitive, and powerful set of tools.
Getting Started: Base R Strings
Section titled “Getting Started: Base R Strings”First, let’s cover the basics. Internally, R stores all strings with double quotes.
# These are all valid stringsstring1 <- 'A string with single quotes.'string2 <- "A string with double quotes."string3 <- "You can include 'single' quotes inside double quotes."string4 <- 'You can include "double" quotes inside single quotes.'
print(string1)print(string4)Output:
[1] "A string with single quotes."[1] "You can include \"double\" quotes inside single quotes."Modern String Manipulation with stringr
Section titled “Modern String Manipulation with stringr”Let’s explore the stringr equivalents of common base R functions. stringr functions are easily recognizable as they all start with str_. First, ensure stringr is installed and loaded.
# install.packages("stringr") # Run once if you don't have itlibrary(stringr)Concatenating Strings: str_c()
Section titled “Concatenating Strings: str_c()”str_c() is the modern alternative to paste(). It’s more intuitive for collapsing vectors into a single string.
first_name <- "Ada"last_name <- "Lovelace"
# Concatenate with a separatorfull_name <- str_c(first_name, last_name, sep = " ")print(full_name)
# Collapse a vector of strings into onecolors <- c("red", "green", "blue")color_list <- str_c(colors, collapse = ", ")print(color_list)Output:
[1] "Ada Lovelace"[1] "red, green, blue"String Length and Subsetting: str_length() and str_sub()
Section titled “String Length and Subsetting: str_length() and str_sub()”my_string <- "R for Data Science"
# Get the number of charactersprint(str_length(my_string))
# Extract a substring from position 7 to 10# Note: str_sub() supports negative indices to count from the endprint(str_sub(my_string, start = 7, end = 10))
# Extract the last 7 charactersprint(str_sub(my_string, start = -7))Output:
[1] 18[1] "Data"[1] "Science"Changing Case and Trimming Whitespace
Section titled “Changing Case and Trimming Whitespace”These are essential for cleaning messy text data.
messy_string <- " Some Text with Mixed Case and whitespace "
# Convert to lower caseprint(str_to_lower(messy_string))
# Convert to upper caseprint(str_to_upper(messy_string))
# Remove leading and trailing whitespaceclean_string <- str_trim(messy_string)print(clean_string)Output:
[1] " some text with mixed case and whitespace "[1] " SOME TEXT WITH MIXED CASE AND WHITESPACE "[1] "Some Text with Mixed Case and whitespace"Pattern Matching with Regular Expressions
Section titled “Pattern Matching with Regular Expressions”stringr excels at pattern matching using regular expressions (regex). This is a powerful way to find, extract, and replace text.
sentences <- c("The price is $19.99.", "The time is 10:30 PM.", "No price here.")
# Detect if a string contains a pattern (e.g., a dollar sign)# The '\$' is escaped with another '\' because '$' is a special regex characterprint(str_detect(sentences, "\\$"))
# Extract the first match of a pattern (e.g., a number)# '\\d+' means 'one or more digits'print(str_extract(sentences, "\\d+"))
# Replace a patternprint(str_replace(sentences, "price", "cost"))Output:
[1] TRUE FALSE TRUE[1] "19" "10" NA[1] "The cost is $19.99." "The time is 10:30 PM." "No cost here."Best Practice: The glue Package for Formatting
Section titled “Best Practice: The glue Package for Formatting”While format() is available, the glue package offers a more modern and readable way to embed variables directly into strings. This is often called string interpolation.
# install.packages("glue") # Run oncelibrary(glue)
user_name <- "Alex"item_count <- 5item_cost <- 15.75total_cost <- item_count * item_cost
# Use glue to create a formatted string# Variables inside {} are automatically evaluated and embeddedmessage <- glue( "Hello, {user_name}!\n" ,"You have ordered {item_count} items.\n" ,"The total cost will be ${total_cost}.")
cat(message) # Use cat() for clean printingOutput:
Hello, Alex!You have ordered 5 items.The total cost will be $78.75.