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" |
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" |
sub("X.*", "", my_string) # Return substring before pattern # "aaa"
Return Substring After Pattern
sub(".*X", "", my_string) # Return substring after pattern # "bbb" |
sub(".*X", "", my_string) # Return substring after pattern # "bbb"