Get startedGet started for free

Combining with stringr functions

You can pass a regular expression as the pattern argument to any stringr function that has the pattern argument. You can use str_detect() to get a logical vector for whether there was a match, str_subset() to return just the strings with matches, and str_count() to count the number of matches in each string.

As a reminder, compare the output of those three functions with our "c_t" pattern from the previous exercise:

x <- c("cat", "coat", "scotland", "tic toc")
pattern <- "c" %R% ANY_CHAR %R% "t"
str_detect(x, pattern)
str_subset(x, pattern)
str_count(x, pattern)

It now also makes sense to add str_extract() to your repertoire. It returns just the part of the string that matched the pattern:

str_extract(x, pattern)

You'll combine your regular expression skills with stringr to ask how often a q is followed by any character in boy names.

It's always a good idea to test your pattern, so this pattern is shown matched with four names. The first two shouldn't have matches (can you explain why?) but the last two should.

This exercise is part of the course

String Manipulation with stringr in R

View Course

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

pattern <- "q" %R% ANY_CHAR

# Find names that have the pattern
names_with_q <- ___

# How many names were there?
___(names_with_q)
Edit and Run Code