Detecting matches
str_detect()
is used to answer the question: Does the string contain the pattern?
It returns a logical vector of the same length as that of the input vector string
, with TRUE
for elements that contain the pattern and FALSE
otherwise.
Let's take a look at a simple example where you have a vector of strings that represent pizza orders:
pizzas <- c("cheese", "pepperoni",
"sausage and green peppers")
You can ask which orders contain the pattern "pepper"
, with
str_detect(pizzas,
pattern = fixed("pepper"))
Try it out! You should get FALSE TRUE TRUE
. Notice how both pepperoni and green peppers contain the pattern of interest.
The output from str_detect()
can be used to count the number of occurrences, or to subset out the strings that contain the pattern. You'll practice both to find the boys' names that contain "zz"
.
This exercise is part of the course
String Manipulation with stringr in R
Exercise instructions
- Use
str_detect()
to find whichboy_names
contain"zz"
. Save the result tocontains_zz
. - Examine the structure of
contains_zz
withstr()
. It should be a logical vector the same length asboy_names
. - To find out how many names in
boy_names
contain"zz"
, usesum()
oncontains_zz
. Recall summing a logical vector counts how many areTRUE
. - To find the names in
boy_names
that contain"zz"
, subsetboy_names
using[
andcontains_zz
. - We've also included
boy_df
in your workspace, a data frame that corresponds to the boys' names in 2014. Subset the rows ofboy_df
usingcontains_zz
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Look for pattern "zz" in boy_names
contains_zz <- ___
# Examine str() of contains_zz
___
# How many names contain "zz"?
___
# Which names contain "zz"?
___
# Which rows in boy_df have names that contain "zz"?
___