Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a stringr equivalent for grep with value = TRUE?

Tags:

r

stringr

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"
like image 673
David Rubinger Avatar asked Jan 18 '18 15:01

David Rubinger


1 Answers

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).

like image 165
James Avatar answered Oct 29 '22 12:10

James