시작하기무료로 시작하기

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

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# 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"?
___
코드 편집 및 실행