9

Is there a stringr equivalent for grep with value set to TRUE? (I would like to avoid the NAs returned by the stringr command below.)

library(stringr)
x <- c("a", "b", "a")
grep("a", x, value = TRUE)  # returns "a" "a"
str_extract(x, "a")  # returns "a" NA  "a"
David Rubinger
  • 3,580
  • 1
  • 20
  • 29

1 Answers1

11

Use str_subset:

str_subset(x,"a")
[1] "a" "a"

The helpfile states the equivalence:

str_subset() is a wrapper around x[str_detect(x, pattern)], and is equivalent to grep(pattern, x, value = TRUE).

James
  • 65,548
  • 14
  • 155
  • 193