R: R String Processing

Last updated: 2026-08-26

In real-world projects, 80% of data cleaning time is spent on string processing—cleaning up phone numbers, extracting email addresses, replacing keywords, and splitting and concatenating strings. The stringr package in R is officially recommended by tidyverse; it is more consistent and easier to use than the standard R grep/gsub package.

After completing this lesson, you’ll be able to use R to handle any text cleaning task: validating phone numbers, extracting email addresses, text segmentation, and URL parsing.

1. What You'll Learn



2. A Story About Data Cleaning

(1) Pain Point: Dirty Data

After receiving a set of customer data, Chen discovered that:

TEXT 📖 Display only
Name      Cell phone number            Email
Alice      138-0000-1234     zhangsan@163.COM
Bob      +86 139 0000 5678  lisi@example.com  
Charlie      (13900001111)    wangwu@gmail.com
Diana      138.0000.2222     zhaoliu@ qq.com
Eve      13900003333       

To be cleaned to:

TEXT 📖 Display only
Name      Cell phone number       Email
Alice      13800001234  zhangsan@163.com
Bob      13900005678  lisi@example.com
Charlie      13900001111  wangwu@gmail.com
Diana      13800002222  zhaoliu@qq.com
Eve      13900003333  NA

If you use Excel formulas and make manual adjustments, it takes half an hour; with Python’s re module, it takes 20 lines of code; with R stringr

(2) Solution using R

R
library(stringr)

# 1. Delete a Phone Number(Remove spaces,-,.,+86,())
clean_phone <- str_replace_all(phones, "[\\s\\-\\.\\(\\)\\+86]", "")

# 2. Clean Up Your Inbox(Remove spaces,Convert to lowercase)
clean_email <- str_trim(emails) |> str_to_lower()

# 3. Verify the mobile phone number format
is_valid_phone <- str_detect(clean_phone, "^1[3-9]\\d{9}$")

5 cleaning tasks completed with just 3 lines of code.

100%
graph LR
    A[Dirty Strings<br/>' 138-0000-1234 '] --> B[str_trim Remove spaces]
    B --> C[str_replace_all Remove special characters]
    C --> D[str_to_lower Use all lowercase letters]
    D --> E[str_detect Validation Format]
    E --> F[Clean String<br/>'13800001234']

    style A fill:#f8d7da
    style B fill:#fff3cd
    style C fill:#d4edda
    style D fill:#cce5ff
    style E fill:#e1d4ff
    style F fill:#d4edda


3. String Basics

(1) Creating Strings

R
# 1. Single quotation mark
s1 <- 'Hello'

# 2. Double quotation marks
s2 <- "World"

# 3. Character vector
fruits <- c("Apple", "Banana", "Cherries")
class(fruits)
# [1] "character"

# 4. nchar Number of characters
nchar("Hello")
# [1] 5

nchar("Hello")  # UTF-8 One Chinese character 1 characters
# [1] 2

(2) paste() / paste0() Concatenation

R
# paste Default sep = " "
paste("Hello", "World")
# [1] "Hello World"

# paste0 No separators
paste0("Hello", "World")
# [1] "HelloWorld"

# Vectorized Concatenation
paste("No.", 1:3, "Place")
# [1] "No. 1 Place" "No. 2 Place" "No. 3 Place"

# collapse Combine vectors into a single string
paste(c("A", "B", "C"), collapse = "-")
# [1] "A-B-C"


4. The stringr Package: 5 Key Functions

100%
mindmap
    root((stringr<br/>5 Major Core Functions))
        Concatenation
            str_c
            str_glue
        Substring
            str_sub
            str_length
        Testing
            str_detect
            str_count
        Replace
            str_replace
            str_replace_all
        Split
            str_split
        Support
            str_trim
            str_pad
            str_to_upper
            str_to_lower
        Advantages
            Automated Processing NA
            API Match
            Pipe-Friendly
            tidyverse Ecology

(1) Comparison of stringr vs. Basic R

Basic R stringr Advantages
nchar() str_length() stringr automatically handles NA
paste() str_c() Consistency + Vectorization
substr() str_sub() Supports negative indexes
More intuitive
gsub() str_replace_all() Simpler
strsplit() str_split() Easier to use

(2) str_c() concatenation

R
library(stringr)

# 1. Basic Splicing
str_c("Hello", "World", sep = " ")
# [1] "Hello World"

# 2. Multi-Parameter Concatenation
str_c("a", "b", "c", sep = "-")
# [1] "a-b-c"

# 3. Vectorized Concatenation
str_c("No.", 1:3, "Place", sep = "")
# [1] "No.1Place" "No.2Place" "No.3Place"

# 4. collapse Merge Vectors
str_c(c("A", "B", "C"), collapse = " | ")
# [1] "A | B | C"

# 5. Processing NA
str_c("Hello", NA, "World")
# [1] NA
str_c("Hello", NA, "World", na.rm = TRUE)
# [1] "HelloWorld"

(3) str_length() Length

R
# Number of characters(Not the number of bytes)
str_length("Hello")
# [1] 5

str_length("Hello")
# [1] 2

# String Vectors
str_length(c("abc", "Hello", "Hello World"))
# [1]  3  2 12

# NA Processing
str_length(NA)
# [1] NA  ← stringr Explicit Return NA

(4) str_sub() Substring

R
# 1. Extract a Substring(1-based,Including both ends)
str_sub("Hello World", 1, 5)
# [1] "Hello"

# 2. Negative Index(From the last digit)
str_sub("Hello World", -5)  # Finally 5 ea
# [1] "World"

# 3. Modify a Substring
s <- "Hello World"
str_sub(s, 1, 5) <- "Hi"
s
# [1] "Hi World"

# 4. Vectorization
str_sub(c("apple", "banana", "cherry"), 1, 3)
# [1] "app" "ban" "che"

(5) str_detect() Detection

R
# 1. Does it contain a substring?
str_detect("Hello World", "World")
# [1] TRUE

# 2. Using regular expressions
str_detect(c("apple", "banana", "cherry"), "^a")  # Starting with a
# [1]  TRUE FALSE FALSE

# 3. Count(Includes several times)
str_count("ababab", "ab")
# [1] 3

(6) str_replace() / str_replace_all() Replacement

R
# 1. Replace the first match
str_replace("Hello World World", "World", "R")
# [1] "Hello R World"

# 2. Replace all matches
str_replace_all("Hello World World", "World", "R")
# [1] "Hello R R"

# 3. Using regular expressions
str_replace_all("abc 123 def 456", "\\d+", "X")
# [1] "abc X def X"


5. Handling Spaces and Formatting

(1) str_trim() removes whitespace

R
# 1. Remove leading and trailing spaces
str_trim("  Hello World  ")
# [1] "Hello World"

# 2. Left edge
str_trim("  Hello", side = "left")
# [1] "Hello"

# 3. Go to the right end
str_trim("Hello  ", side = "right")
# [1] "Hello"

(2) str_pad() Padding

R
# 1. Left-aligned
str_pad("42", width = 5, side = "left", pad = "0")
# [1] "00042"

# 2. Right-aligned
str_pad("Hi", width = 5, side = "right", pad = "-")
# [1] "Hi---"

# 3. Filled on both sides
str_pad("Hi", width = 6, side = "both", pad = "-")
# [1] "--Hi--"

(3) str_to_* Case Sensitivity

R
# 1. All Caps
str_to_upper("Hello World")
# [1] "HELLO WORLD"

# 2. All lowercase
str_to_lower("Hello World")
# [1] "hello world"

# 3. Capitalize the first letter
str_to_title("hello world")
# [1] "Hello World"

# 4. Capitalize the first word of a sentence
str_to_sentence("hello world")
# [1] "Hello world"

(4) str_trunc() Truncate

R
# Truncate excessively long strings(add ...)
str_trunc("This is a very long sentence.", width = 10)
# [1] "This is..."


6. str_split() Splitting

R
# 1. Basic Division
str_split("a,b,c", ",")
# [[1]]
# [1] "a" "b" "c"

# 2. Limit on the Number of Partitions
str_split("a,b,c", ",", n = 2)
# [[1]]
# [1] "a"     "b,c"

# 3. Simplify the result(Vectors, Not Lists)
str_split("a,b,c", ",", simplify = TRUE)
#      [,1] [,2] [,3]
# [1,] "a"  "b"  "c"


7. Hands-On: Cleaning Customer Data

Below is an example of a complete workflow that brings together all the string concepts covered in this lesson.

▶ Example: In-Depth Cleaning of Customer Data

R 📖 Display only
# ============================================
# In-Depth Cleaning of Customer Data
# Features:Delete a Phone Number,Email,Name,Address
# ============================================

library(stringr)
library(dplyr)

# 1. Preparing Raw Data
customers <- tibble(
  name = c("  Alice  ", "Bob", "wangwu", "ZHAO liu", "Eve"),
  phone = c("138-0000-1234", "+86 139 0000 5678", "(13900001111)",
            "138.0000.2222", "13900003333"),
  email = c("zhangsan@163.COM", " lisi@example.com  ",
            "wangwu@gmail.com", "zhaoliu@ qq.com", NA)
)

cat("=== Raw Data ===\n")
print(customers)

# 2. Clean Name
customers <- customers |>
  mutate(
    # Remove spaces + Capitalize the first letter(English Name)
    name_clean = str_trim(name) |>
      str_to_title() |>
      str_replace_all("\\s+", " ")  # Replace multiple spaces with a single space
  )

# 3. Delete a Phone Number(Remove spaces,-,.,+86,())
customers <- customers |>
  mutate(
    phone_clean = str_replace_all(phone, "[\\s\\-\\.\\(\\)\\+86]", ""),
    # Verification 11 Mobile phone number
    phone_valid = str_detect(phone_clean, "^1[3-9]\\d{9}$")
  )

# 4. Clean Up Your Inbox
customers <- customers |>
  mutate(
    email_clean = str_trim(email) |> str_to_lower(),
    # Verify the email address format
    email_valid = str_detect(email_clean, "^[\\w.+-]+@[\\w.-]+\\.[a-z]{2,}$")
  )

# 5. Output the cleaning results
cat("\n=== Data After Cleaning ===\n")
print(customers |> select(name_clean, phone_clean, phone_valid,
                          email_clean, email_valid))

# 6. Extracting Data Features
customers <- customers |>
  mutate(
    # Identify the mobile carrier based on a phone number
    operator = case_when(
      str_detect(phone_clean, "^1(3[0-9]|4[5-9]|5[0-35-9]|66|7[2-35-8]|8[0-9]|9[0-35-9])\\d{8}$") ~ "China Mobile",
      str_detect(phone_clean, "^1(3[0-2]|4[5-7]|5[3-5-7]|6[2567]|7[0-3]|8[0-3])\\d{8}$") ~ "China Unicom",
      str_detect(phone_clean, "^1(33|34|49|53|7[37]|8[0-2])\\d{8}$") ~ "China Telecom",
      TRUE ~ "Unknown"
    ),
    # Email Domain
    email_domain = str_extract(email_clean, "@[a-z0-9.]+"),
    # Before the phone number 3 bit
    phone_prefix = str_sub(phone_clean, 1, 3)
  )

cat("\n=== Data Characteristics ===\n")
print(customers |> select(name_clean, operator, phone_prefix, email_domain))

# 7. Text Statistics
cat("\n=== Distribution of Email Domain Names ===\n")
print(table(customers$email_domain))

cat("\n=== Distribution of Carriers ===\n")
print(table(customers$operator))

# 8. Identify invalid data
cat("\n=== Invalid data ===\n")
invalid <- customers |> filter(!phone_valid | !email_valid)
print(invalid |> select(name_clean, phone_clean, phone_valid,
                        email_clean, email_valid))
51 logic lines (exceeds 40-line limit, display only)

Expected Output (Excerpt):

TEXT 📖 Display only
=== Data After Cleaning ===
# A tibble: 5 × 6
  name_clean phone_clean   phone_valid email_clean         email_valid
  <chr>      <chr>         <lgl>       <chr>               <lgl>      
1 Alice       13800001234   TRUE        zhangsan@163.com    TRUE       
2 Bob       13900005678   TRUE        lisi@example.com    TRUE       
3 Wangwu     13900001111   TRUE        wangwu@gmail.com    TRUE       
4 Zhao Liu   13800002222   TRUE        zhaoliu@qq.com      TRUE       
5 Eve       13900003333   TRUE        <NA>                FALSE      

=== Distribution of Carriers ===
  China Telecom China Unicom China Mobile 
        1        2        2

❓ FAQ

Q How do I choose between stringr and the basic R string functions?
A Use stringr for new projects
Q How do you use negative indices with str_sub()?
A Negative numbers start from the end. str_sub(x, -3) retrieves the last 3 characters; str_sub(x, 1, -2) retrieves everything from the beginning up to the second-to-last character.
Q What is the difference between str_replace() and str_replace_all()?
A str_replace replaces only the first match, while str_replace_all replaces all matches. In most cases, use str_replace_all.
Q How do I extract numbers?
A str_extract_all(x, "\\d+") Extracts all numeric strings (list). str_extract(x, "\\d+") Extracts the first number (vector).
Q What should I do if Chinese characters appear as garbled text?
A R 4.x uses UTF-8 by default, so there should be no garbled text. If you do encounter garbled text, use stringi::stri_encode() to convert the encoding, or use locale = locale(encoding = "GBK") when reading the file.
Q What is the difference between str_c() and paste()?
A They are essentially equivalent. However, str_c() offers better consistency (it propagates NA values by default) and is more readable when used with pipes.

📖 Summary


📝 Exercises

  1. Basic Problem: Use str_c() to concatenate vectors c("Apple", "Banana", "Cherry") and c(1, 2, 3), and output "Apples 1 yuan," "Bananas 2 yuan," and "Cherries 3 yuan."

  2. Basic Problems: Use str_length() to calculate the number of characters in "Hello World", "Hello World", and "". Use str_sub() to extract the 7th through 11th characters of "Hello World."

  3. Basic Problem: Use str_detect() to determine which elements in c("apple", "banana", "cherry") end with "a," and output a logical vector.

  4. Advanced Exercise: Clean the following dirty data: ① Remove spaces from email addresses and convert them to lowercase; ② Extract the email domain; ③ Validate the email format (@ + domain + . + at least 2 letters). Use mutate() to add 3 new columns of data.

  5. Challenge: Simulate 100 lines of customer data (including various invalid phone numbers, email addresses, and names) and complete the following data cleansing process: ① Cleanse names ② Cleanse phone numbers ③ Verify phone numbers ④ Cleanse email addresses ⑤ Extract carrier information ⑥ Calculate the percentage of invalid data. Print out the data frames before and after cleansing, and save screenshots of them.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏