You can use the following methods to find the location of a character in a string in R:
Method 1: Find Location of Every Occurrence
unlist(gregexpr('character', my_string))
Method 2: Find Location of First Occurrence
unlist(gregexpr('character', my_string))[1]
Method 3: Find Location of Last Occurrence
tail(unlist(gregexpr('character', my_string)), n=1)
Method 4: Find Total Number of Occurrences
length(unlist(gregexpr('character', my_string)))
The following examples show how to use each method in practice.
Method 1: Find Location of Every Occurrence
The following code shows how to find every location of the character “a” in a certain string:
#define string my_string = 'mynameisronalda' #find position of every occurrence of 'a' unlist(gregexpr('a', my_string)) [1] 4 12 15
From the output we can see that the character “a” occurs in position 4, 12, and 15 of the string.
Method 2: Find Location of First Occurrence
The following code shows how to find the location of the first occurrence of the character “a” in a certain string:
#define string my_string = 'mynameisronalda' #find position of first occurrence of 'a' unlist(gregexpr('a', my_string))[1] [1] 4
From the output we can see that the character “a” first occurs in position 4 of the string.
Method 3: Find Location of Last Occurrence
The following code shows how to find the location of the last occurrence of the character “a” in a certain string:
#define string my_string = 'mynameisronalda' #find position of last occurrence of 'a' tail(unlist(gregexpr('a', my_string)), n=1) [1] 15
From the output we can see that the last occurrence of the character “a” is in position 15 of the string.
Method 4: Find Total Number of Occurrences
The following code shows how to find the total number of occurrences of the character “a” in a certain string:
#define string my_string = 'mynameisronalda' #find total occurrences of 'a' length(unlist(gregexpr('a', my_string))) [1] 3
From the output we can see that the character “a” occurs 3 times in the string.
Additional Resources
The following tutorials explain how to perform other common operations in R:
How to Concatenate Strings in R
How to Convert a Vector to String in R
How to Convert Character to Factor in R