str_starts & str_ends Functions in R (2 Examples)

 

In this article, I’ll illustrate how to apply str_starts and str_ends to detect the presence or absence of a pattern at the beginning or end of character strings in the R programming language.

Table of contents:

Let’s do this:

 

Creation of Example Data

I’ll use the following character string in the examples of this R tutorial:

x <- c("hey, look at my string")         # Create a character string

Since we want to apply the str_starts and str_ends functions of the stringr add-on package, we also need to install and load the package to R:

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

 

Example 1: Application of str_starts Function in R

This section explains how to apply the str_starts function in R. Have a look at the following R code:

str_starts(x, "hey")                     # Apply str_starts function
# TRUE

The previous R syntax checked whether our character string starts with the pattern “hey”. Since this is the case, the str_starts function returns the logical value TRUE.

 

Example 2: Application of str_ends Function in R

We can use a similar procedure with the str_ends function:

str_ends(x, "hey")                       # Apply str_ends function
# FALSE

With the previous R code, we evaluated whether our character string ends with the pattern “hey”. Since this is not the case, the str_ends command returns the logical value FALSE.

 

Video & Further Resources

In case you need further info on the R programming codes of this tutorial, I can recommend to watch the following video of my YouTube channel. In the video, I explain the R programming codes of this tutorial:

 

The YouTube video will be added soon.

 

Furthermore, I can recommend to read the other tutorials of my website. A selection of tutorials is shown here:

 

In this R tutorial you learned how to find out whether a pattern exists at the beginning or end of a character string. If you have any further questions, let me know in the comments section 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