OneBite.Dev - Coding blog in a bite size

find the position of the last occurrence of a substring in a string in R

Code snippet on how to find the position of the last occurrence of a substring in a string in R

gregexpr("substring", "string", fixed = TRUE)[1][2]

This code finds the position of the last occurrence of a substring in a string using the gregexpr function in R. This function returns a list of vectors with the starting and ending positions of a match in the character vecror. By using fixed = TRUE, the function uses substring as a literal string instead of a regular expression. The [1][2] is used to return the last index which is the position of the last occurrence of the substring.

r