str_locate & str_locate_all Functions in R (2 Examples)

 

In this R tutorial you’ll learn how to use str_locate and str_locate_all to locate the position of patterns in a character string.

Table of contents:

With that, here’s the step-by-step process.

 

Example Data

As a first step, we have to create an exemplifying character string in R:

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

In addition, we 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_locate Function in R

In Example 1, I’ll show you how to apply the str_locate function. Have a look at the following R code:

str_locate(x, "mple")             # Apply str_locate function
#      start end
# [1,]     7  10

As you can see, the str_locate command returns a matrix containing a starting and an ending value. In this example, the pattern “mple” begins at the 7th character and ends at the 10th character of our string.

 

Example 2: Application of str_locate_all Function in R

The str_locate function, which I have explained in Example 1, returns only the first occurrence of a certain pattern. If we want to extract all locations of such a pattern, we need to use the str_locate_all function:

str_locate_all(x, "m")            # Apply str_locate_all function
# [[1]]
#      start end
# [1,]     1   1
# [2,]     7   7

As you can see based on the previous output, the letter “m” occurs at the first and at the 7th position of our character string.

 

Video & Further Resources

Have a look at the following video tutorial of my YouTube channel. I’m explaining the R programming syntax of this tutorial in the video:

 

The YouTube video will be added soon.

 

Furthermore, you may read the other tutorials on https://statisticsglobe.com/:

 

To summarize: This article explained how to identify the positioning of certain characters in a string in R. In case you have any additional questions and/or comments, please tell me about it in the comments. Furthermore, please subscribe to my email newsletter in order to get updates on the newest articles.

 

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