12

Is there an stringr equivalent to base R's grep function?

I want to have the index of the string that matches. Example:

grep("F|Y", LETTERS)
[1]  6 25

With stringr my workaround would be using which as follows:

which(str_detect(LETTERS, "F|Y"))
[1]  6 25
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
Rentrop
  • 20,979
  • 10
  • 72
  • 100
  • I don't use stringr, but see if `str_locate` is what you need. – R. Schifini Jun 23 '16 at 15:56
  • 1
    `str_locate` returns a matrix of start/end columns. I think the OP is looking for the index without using `which` – akrun Jun 23 '16 at 16:01
  • @akrun yes. Thats what i am looking for – Rentrop Jun 23 '16 at 16:59
  • 1
    As the man pages for `stringr` are quite clear and unambiguous, there's no doubt that none of the functions return just the indices. So (as us DataMungerGuru Accolytes always ask), *why* do you want to do this? What is the problem you are trying to solve? – Carl Witthoft Jun 23 '16 at 17:18
  • @CarlWitthoft I am porting my code from base R to _stringr_. As this is my first time using _stringr_ i dont want to start with using wrong functions. Thats why i am asking here... – Rentrop Jun 24 '16 at 09:53

2 Answers2

20

Sorry for the late answer but it might be helpful for future visitors:

Now you can use str_which(string, pattern) which is a wrapper around which(str_detect(string, pattern)) and equivalent to grep(pattern, string).

str_which(LETTERS, "F|Y")
[1]  6 25

More details at: http://stringr.tidyverse.org/reference/str_subset.html

allanvc
  • 1,096
  • 10
  • 23
-1

With the new update string_like will also be applicable.

which(str_like(LETTERS, "F|Y"))

Read more about the stringr updates that are linked below. Hope this helps everyone.