+1 vote
in Programming Languages by (40.7k points)
I want to find the index of a character in a given string. Which R function should I use for it?

1 Answer

+1 vote
by (157k points)
selected by
 
Best answer

You can use functions unlist() and gregexpr() to find the position of a character in a string. If the character appears more than once in the string, you will get all positions.

Here is an example:

> r = "helloarielprinter"
> unlist(gregexpr('p', r))
[1] 11
> unlist(gregexpr('e', r))
[1]  2  9 16

The first argument in the function gregexpr() is the character you are trying to search for, and the second argument is the string.


...