OneBite.Dev - Coding blog in a bite size

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

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

  str_locate_first(string = "Hello World!", pattern = "o")

This code searches for the first occurrence of the substring “o” within the string “Hello World!“. The function str_locate_first() returns the starting position of the substring. The output will look like this: [6, 1] which in this case means that the substring “o” starts at the position 6, in the first phrase of the string. If the substring is not found within the string, the output will be [NA, -1].

r