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".
이 연습은 강의의 일부입니다
String Manipulation with stringr in R
연습 안내
- 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.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# 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"?
___