str_detect Function in R (stringr Package)

 

In this article you’ll learn how to use the str_detect function to detect the presence or absence of a pattern in a character string in R.

Table of contents:

It’s time to dive into the examples:

 

Creation of Example Data

In the example of this tutorial, we’ll use the following exemplifying character string:

x <- "hello R user, this is my string"   # Create example character string

As you can see, our example string contains a simple sentence stored in the data object x.

 

Example: Application of str_detect Function in R

Before the application of the str_detect command, we need to install and load the stringr package to R:

install.packages("stringr")              # Install stringr package
library("stringr")                       # Load stringr package

Now, we can apply the str_detect function as shown below:

str_detect(x, "is")                      # Apply str_detect function
# TRUE

The previous R code checks whether the pattern “is” is contained within our example string x.

As you can see based on the output of the RStudio console, the str_detect function returns a logical value (i.e. FALSE or TRUE), showing whether the pattern is present in our character string.

In our example, the str_detect function returns the value TRUE, i.e. the pattern “is” is present in our example string.

 

Video, Further Resources & Summary

Some time ago I have published a video on my YouTube channel, which explains the examples of this tutorial. Please find the video below.

 

The YouTube video will be added soon.

 

Also, you might want to have a look at some of the other articles that I have published on my website. Some articles are listed below:

 

In summary: In this post, I explained how to check for the presence or absence of a pattern in a string in the R programming language. Let me know in the comments section below, in case you have additional questions.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top