substr & substring Functions in R (3 Examples)

This page shows how to apply the substr and substring functions in the R programming language.

Depending on the task you want to accomplish, substr() or substring() is preferable. In the following examples, you’ll learn when to use which of the two functions.

Note that in some situations both functions may be used.

Example Data

my_string <- "this is my character string"               # Example string

Example 1: Extract Certain Characters from String (substr Function)

substr(my_string, start = 9, stop = 20)                  # Extract certain characters

Example 2: Extract Characters Starting at Certain Position (substring Function)

substring(my_string, first = 9)                          # From position to the right

Example 3: Replace Certain Characters in String (substr Function)

substr(my_string, start = 12, stop = 20) <- "beautiful"  # Replace certain characters
my_string                                                # Print updated string
# "this is my beautiful string"

Video Examples


By loading the video, you agree to YouTube’s privacy policy.
Learn more

Load video

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.
You need to agree with the terms to proceed