Skip to content

R - Strings

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.

First, let’s cover the basics. Internally, R stores all strings with double quotes.

# These are all valid strings
string1 <- '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."

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 it
library(stringr)

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 separator
full_name <- str_c(first_name, last_name, sep = " ")
print(full_name)
# Collapse a vector of strings into one
colors <- 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 characters
print(str_length(my_string))
# Extract a substring from position 7 to 10
# Note: str_sub() supports negative indices to count from the end
print(str_sub(my_string, start = 7, end = 10))
# Extract the last 7 characters
print(str_sub(my_string, start = -7))

Output:

[1] 18
[1] "Data"
[1] "Science"

These are essential for cleaning messy text data.

messy_string <- " Some Text with Mixed Case and whitespace "
# Convert to lower case
print(str_to_lower(messy_string))
# Convert to upper case
print(str_to_upper(messy_string))
# Remove leading and trailing whitespace
clean_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"

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 character
print(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 pattern
print(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 once
library(glue)
user_name <- "Alex"
item_count <- 5
item_cost <- 15.75
total_cost <- item_count * item_cost
# Use glue to create a formatted string
# Variables inside {} are automatically evaluated and embedded
message <- 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 printing

Output:

Hello, Alex!
You have ordered 5 items.
The total cost will be $78.75.