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".
Este exercício faz parte do curso
String Manipulation with stringr in R
Instruções do exercício
- Use
str_detect()to find whichboy_namescontain"zz". Save the result tocontains_zz. - Examine the structure of
contains_zzwithstr(). It should be a logical vector the same length asboy_names. - To find out how many names in
boy_namescontain"zz", usesum()oncontains_zz. Recall summing a logical vector counts how many areTRUE. - To find the names in
boy_namesthat contain"zz", subsetboy_namesusing[andcontains_zz. - We've also included
boy_dfin your workspace, a data frame that corresponds to the boys' names in 2014. Subset the rows ofboy_dfusingcontains_zz.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# 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"?
___