Searching Strings
Part of the Logic & Flow section of Coddy's R journey. Lesson 4 of 64.
grepl(pattern, x) returns TRUE for each element of x that contains pattern. Add fixed = TRUE to search for the exact characters. Without it the pattern is a regular expression, where characters such as . and ? have special meanings.
files <- c("report.csv", "photo.png", "data.csv")
print(grepl(".csv", files, fixed = TRUE))
print(files[grepl(".csv", files, fixed = TRUE)])Output:
[1] TRUE FALSE TRUE
[1] "report.csv" "data.csv" startsWith(x, prefix) and endsWith(x, suffix) check only the beginning or the end of each string. All of these searches are case sensitive, so convert with tolower() first to ignore case.
names <- c("Anna", "bob", "Andre")
print(startsWith(names, "An"))
print(startsWith(tolower(names), "b"))Output:
[1] TRUE FALSE TRUE
[1] FALSE TRUE FALSEThe results are logical vectors, so sum() counts the matches and any() checks for at least one:
emails <- c("a@x.com", "bad-address", "c@y.org")
valid <- grepl("@", emails, fixed = TRUE)
print(sum(valid))
print(any(!valid))Output:
[1] 2
[1] TRUEgrep(pattern, x) returns the positions of the matching elements, and grep(pattern, x, value = TRUE) the elements themselves:
files <- c("a.csv", "b.txt", "c.csv")
print(grep(".csv", files, fixed = TRUE))
print(grep(".csv", files, fixed = TRUE, value = TRUE))Output:
[1] 1 3
[1] "a.csv" "c.csv"Challenge
EasyComplete count_domain(emails, domain). Return how many addresses in emails end with @ followed by domain. Ignore case: CY@CODDY.TECH counts for the domain coddy.tech.
The supplied code reads the addresses as a comma-separated line, then the domain, and prints the returned number.
Try it yourself
count_domain <- function(emails, domain) {
# Write your code here
0
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
emails <- strsplit(input[1], ",")[[1]]
cat(count_domain(emails, input[2]), 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