Return Characters Before / After Particular Pattern in String in R (Example)

In the following R programming tutorial, you’ll learn how to extract a substring before or after a certain pattern in R.

Example String

my_string <- "aaaXbbb"            # Our character string
my_string                         # Print the string
# "aaaXbbb"

Our example character string contains three times the letter “a” before the pattern “X” and three times the latter “b” after the pattern “X”.

Return Substring Before Pattern

sub("X.*", "", my_string)         # Return substring before pattern
# "aaa"

Return Substring After Pattern

sub(".*X", "", my_string)         # Return substring after pattern
# "bbb"

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top