CommencerCommencer gratuitement

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".

Cet exercice fait partie du cours

String Manipulation with stringr in R

Afficher le cours

Instructions

  • Use str_detect() to find which boy_names contain "zz". Save the result to contains_zz.
  • Examine the structure of contains_zz with str(). It should be a logical vector the same length as boy_names.
  • To find out how many names in boy_names contain "zz", use sum() on contains_zz. Recall summing a logical vector counts how many are TRUE.
  • To find the names in boy_names that contain "zz", subset boy_names using [ and contains_zz.
  • We've also included boy_df in your workspace, a data frame that corresponds to the boys' names in 2014. Subset the rows of boy_df using contains_zz.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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"?
___
Modifier et exécuter le code