Menu
Coddy logo textTech

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 FALSE

The 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] TRUE

grep(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 icon

Challenge

Easy

Complete 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")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler