How to Use str_detect() Function in R (3 Examples)


You can use the str_detect() function from the stringr function R to detect the presence or absence of a certain pattern in a string.

This function uses the following basic syntax:

library(stringr)

#check if "hey" exists in object named x
str_detect(x, "hey")

This function returns TRUE if the pattern is present in the string or FALSE if it is not.

The following examples show how to use this function in different scenarios.

Example 1: Use str_detect() with String

The following code shows how to use the str_detect() function to detect if the pattern “hey” is present in a certain string:

library(stringr)

#create string
x <- "hey there everyone"

#determine if "hey" is present in string
str_detect(x, "hey")

[1] TRUE

From the output we can see that “hey” is present in the string.

Note that str_detect() is case-sensitive as well:

library(stringr)

#create string
x <- "hey there everyone"

#determine if "Hey" is present in string
str_detect(x, "Hey")

[1] FALSE

From the output we can see that “Hey” is not present in the string.

Example 2: Use str_detect() with Vector

The following code shows how to use the str_detect() function to detect if the pattern “hey” is present in each individual element of a vector:

library(stringr)

#create vector
x <- c("hello", "heyo", "hi", "hey")

#determine if "hey" is present in each element of vector
str_detect(x, "hey")

[1] FALSE  TRUE FALSE  TRUE

From the output we can see that “hey” in just the second and fourth elements of the vector.

Example 3: Use str_detect() with Data Frame

The following code shows how to use the str_detect() function to subset a data frame based on the values in one column having “avs” in the name:

library(stringr)

#create data frame
df <- data.frame(team=c("Mavs", "Heat", "Pacers", "Cavs"),
                 points=c(99, 90, 86, 103))	

#subset data frame based on teams that have "avs" in the name
df[str_detect(df$team, "avs"), ]

  team points
1 Mavs     99
4 Cavs    103

Notice that only the teams that have “avs” in the name are included in the final data frame.

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Use length() Function in R
How to Use cat() Function in R
How to Use substring() Function in R

Leave a Reply

Your email address will not be published.