str_match & str_match_all Functions in R (2 Examples)

 

In this tutorial you’ll learn how to apply str_match and str_match_all to extract matched groups from a string in R.

The tutorial contains this information:

So now the part you have been waiting for – the examples…

 

Creation of Example Data

Before we can apply the str_match and str_match_all functions, we need to create a character string in R:

x <- c("my example string")       # Create character string

Then, we also have to install and load the stringr package of the tidyverse to R:

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

 

Example 1: Application of str_match Function in R

In Example 1, I’ll show you how to apply the str_match function. First, we will check whether the letter “m” is contained in our example character string x:

str_match(x, "m")                 # Apply str_match function
#      [,1]
# [1,] "m"

The str_match function is returning a matrix, which contains the value “m”. In other words, yes there was a match!

Let’s see what happens when we check for a different pattern:

str_match(x, "yyy")               # Apply str_match function
#      [,1]
# [1,] NA

As you can see, the str_match command returns a matrix containing an NA value. The pattern “yyy” is not existing in our character string.

 

Example 2: Application of str_match_all Function in R

The str_match command of Example 1 returns only the first matching pattern. However, with the str_match_all function we can return all matching pattern in a matrix:

str_match_all(x, "m")             # Apply str_match_all function
# [[1]]
#      [,1]
# [1,] "m" 
# [2,] "m"

The letter “m” occurs twice in our example string.

 

Video & Further Resources

Do you want to learn more about the handling of strings in R? Then you could have a look at the following video of my YouTube channel. In the video, I’m explaining the R programming syntax of this tutorial in a live session:

 

The YouTube video will be added soon.

 

Furthermore, I can recommend to read the other articles of statisticsglobe.com. I have released numerous other articles already.

 

You learned in this tutorial how to return matched groups from a character string in the R programming language. In case you have any additional questions, let me know in the comments below.

 

Subscribe to the Statistics Globe 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.

Top