Extract Leading or Trailing N Characters from String in R (Example)

This R syntax shows how to extract the first or last N characters from a string in the R programming language.

Example Data

my_string <- "what a beautiful character string"

Return First N Characters from String

If we want to extract N leading characters from a string, we can use the substr function in R as follows:

substr(my_string, 1, 10)
# "what a bea"

Return Last N Characters from String

If we want to get N trailing elements from a character string, we can use a combination of substr and nchar:

substr(my_string, nchar(my_string) - 10 + 1, nchar(my_string))
# "ter string"

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