How to Find Location of Character in a String in R

In R, the location of a character in a string can be found using the substr() function. This function takes three arguments: the string, the starting index of the character to be extracted, and the number of characters to be extracted. The returned result is the extracted characters from the specified location of the string. The index starts from 1, and the length of the string can be found using the nchar() function.


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

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.

The following tutorials explain how to perform other common operations in R:

x