Find the location of a character in string Find the location of a character in string r r

Find the location of a character in string


You can use gregexpr

 gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")[[1]][1]  4 24attr(,"match.length")[1] 1 1attr(,"useBytes")[1] TRUE

or perhaps str_locate_all from package stringr which is a wrapper for gregexpr stringi::stri_locate_all (as of stringr version 1.0)

library(stringr)str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired")[[1]]     start end[1,]     4   4[2,]    24  24

note that you could simply use stringi

library(stringi)stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE)

Another option in base R would be something like

lapply(strsplit(x, ''), function(x) which(x == '2'))

should work (given a character vector x)


Here's another straightforward alternative.

> which(strsplit(string, "")[[1]]=="2")[1]  4 24


You can make the output just 4 and 24 using unlist:

unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired"))[1]  4 24