开始使用免费开始使用

Combining with stringr functions

You can pass a regular expression as the pattern argument to any stringr function that has the pattern argument. You can use str_detect() to get a logical vector for whether there was a match, str_subset() to return just the strings with matches, and str_count() to count the number of matches in each string.

As a reminder, compare the output of those three functions with our "c_t" pattern from the previous exercise:

x <- c("cat", "coat", "scotland", "tic toc")
pattern <- "c" %R% ANY_CHAR %R% "t"
str_detect(x, pattern)
str_subset(x, pattern)
str_count(x, pattern)

It now also makes sense to add str_extract() to your repertoire. It returns just the part of the string that matched the pattern:

str_extract(x, pattern)

You'll combine your regular expression skills with stringr to ask how often a q is followed by any character in boy names.

It's always a good idea to test your pattern, so this pattern is shown matched with four names. The first two shouldn't have matches (can you explain why?) but the last two should.

本练习是课程的一部分

String Manipulation with stringr in R

查看课程

交互式实操练习

通过完成这段示例代码来试试这个练习。

pattern <- "q" %R% ANY_CHAR

# Find names that have the pattern
names_with_q <- ___

# How many names were there?
___(names_with_q)
编辑并运行代码