Replacing Text
Part of the Logic & Flow section of Coddy's R journey. Lesson 5 of 64.
sub(pattern, replacement, x) replaces the first match in each string, and gsub() replaces every match. As with grepl(), fixed = TRUE treats the pattern as plain text.
date <- "2024-01-15"
print(sub("-", "/", date, fixed = TRUE))
print(gsub("-", "/", date, fixed = TRUE))Output:
[1] "2024/01-15"
[1] "2024/01/15"Replacing with an empty string deletes the matches. This cleans text before converting it to a number:
price <- "$1,299.00"
clean <- gsub(",", "", sub("$", "", price, fixed = TRUE), fixed = TRUE)
print(clean)
print(as.numeric(clean) * 2)Output:
[1] "1299.00"
[1] 2598Without fixed = TRUE the pattern is a regular expression. Two useful pieces: [0-9] matches any digit, and + repeats the piece before it one or more times, so " +" matches a run of spaces.
msg <- "call me at 555 0199"
print(gsub(" +", " ", msg))
print(gsub("[0-9]", "#", msg))Output:
[1] "call me at 555 0199"
[1] "call me at ### ####"Like the other string functions, sub() and gsub() work on every element of a vector:
codes <- c("a-1", "b-22", "c-3")
print(gsub("-", "", codes, fixed = TRUE))
print(sub("-[0-9]+", "", codes))Output:
[1] "a1" "b22" "c3"
[1] "a" "b" "c"Challenge
EasyComplete slugify(title). Return the title in lower case, without spaces at the start or end, and with every run of spaces replaced by a single -: Hello World becomes hello-world.
The supplied code reads the title and prints the returned value.
Try it yourself
slugify <- function(title) {
# Write your code here
title
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(slugify(input[1]), sep = "\n")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler