str_extract Function in R (stringr Package)

 

In this tutorial, I’ll explain how to use the str_extract function to extract matching patterns from a character string in the R programming language.

Table of contents:

Let’s start right away!

 

Introduction of Example Data

As a first step, we need to create an example string in R:

x <- "a simple example string"    # Create example character string

As you can see, our example character string simply contains the sentence “a simple example string”. Now, let’s apply the str_extract function of the stringr package to this string…

 

Example: Application of str_extract Function in R

First, we need to install and load stringr:

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

After loading the R package, we can apply the str_extract function as follows:

str_extract(x, "exa")             # Apply str_extract function
# "exa"

Within the previous R code, we checked whether our example string x contains the pattern “exa”. Since our example string contains this character pattern, the str_extract returned the pattern to the RStudio console.

Let’s see what happens when we check for a non-existing pattern:

str_extract(x, "abc")             # Different pattern
# NA

Our example character string does not contain the character pattern “abc”. For that reason, the RStudio console returns NA.

 

Video, Further Resources & Summary

Do you need further information on the contents of this article? Then you could have a look at the following video of my YouTube channel. I’m explaining the R programming syntax of this post in the video instruction:

 

The YouTube video will be added soon.

 

Furthermore, you may want to have a look at the related tutorials of my website. A selection of tutorials about R programming can be found here:

 

In summary: In this R tutorial you learned how to extract matching patterns from a string with the str_extract function. If you have further comments or questions, don’t hesitate to let me know in the comments section below.

 

Subscribe to my free statistics newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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