String Manipulation
Lesson 12 of 14 in Coddy's Data Manipulation in R course.
The stringr package provides a comprehensive set of functions for working with strings.
Loading the stringr package
library(stringr)Pattern Matching
The str_detect() function checks if a pattern exists in a string:
text <- c("apple", "banana", "cherry")
str_detect(text, "an") # Returns: FALSE TRUE FALSEString Replacement
The str_replace() function replaces the first occurrence of a pattern:
text <- "Hello world"
str_replace(text, "world", "R") # Returns: "Hello R"Splitting Strings
Split strings into a character vector with str_split():
text <- "apple,banana,cherry"
str_split(text, ",") # Returns a list: list("apple", "banana", "cherry")Trimming Whitespace
Remove leading and trailing whitespace using str_trim():
text <- " Hello, R! "
str_trim(text) # Returns: "Hello, R!"This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a function that processes a list of email addresses using string manipulation techniques from the stringr package. The function should perform the following operations:
- Extract the username (part before the @) from each email address
- Replace any numbers in the usernames with an underscore (_)
- Use
str_replace_all()with the pattern\\dto replace all digits. For example:str_replace_all(username, "\\d", "_")
- Use
- Capitalize the first letter of each username
- You can use the
str_to_title()function for this. It capitalizes the first letter of each word in a string.
- You can use the
- Trim any leading or trailing whitespace from the processed usernames
- Return the processed usernames as a comma-separated string
- Use
str_c()with the collapse argument to join the usernames. For example:str_c(usernames, collapse = ", ")
- Use
Try it yourself
# Read input
con <- file("stdin", "r")
email_list <- suppressWarnings(readLines(con))
suppressPackageStartupMessages(library(stringr))
process_emails <- function(email_list) {
# Split the email list into individual email addresses
emails <- str_split(email_list, ",\\s*")[[1]]
# TODO: Write your code below to process the email addresses
# 1. Extract usernames
# 2. Replace numbers with underscores
# 3. Capitalize first letter
# 4. Trim whitespace
# 5. Join processed usernames with commas
# Placeholder for processed usernames
processed_usernames <- ""
# Return the processed usernames as a comma-separated string
return(processed_usernames)
}
# Call the function and print the result
result <- process_emails(email_list)
cat(result)