How to grep a vector and return one TRUE or FALSE?

Is there a grep function in R that returns TRUE if a pattern is found anywhere in a given character vector and FALSE otherwise?

All the functions that I see return a vector of the current positions of each element found.

+8
regex r
source share
4 answers

Are you looking for "any"?

 > x<-c(1,2,3,4,5) > x==5 [1] FALSE FALSE FALSE FALSE TRUE > any(x==5) [1] TRUE 

Note that you can also do this for strings

 > x<-c("a","b","c","d") > any(x=="b") [1] TRUE > any(x=="e") [1] FALSE 

And this can be convenient when combined:

 > sapply(c(2,4,6,8,10), function(x){ x%%2==0 } ) [1] TRUE TRUE TRUE TRUE TRUE > any(sapply(c(2,4,6,8,10), function(x){ x%%2!=0 } )) [1] FALSE 
+11
source share

maybe a combination of grepl() and any() ?

as

 > foo = c("hello", "world", "youve", "got", "mail") > any(grepl("world", foo)) [1] TRUE > any(grepl("hi", foo)) [1] FALSE > any(grepl("hel", foo)) [1] TRUE 

your questions are a bit unclear whether you want the last example to return true or not

+21
source share

Perhaps you are looking for grepl() ?

 > grepl("is", c("This", "is", "a", "test", "isn't", "it?")) [1] TRUE TRUE FALSE FALSE TRUE FALSE 

If the first argument is the pattern you are looking for, the second argument is the vector against which you want to match, and the return value is a Boolean vector of the same length that describes whether the pattern was matched with each element.

+19
source share

grepl is what you are looking for

 grepl("is", "This is grepl test") [1] TRUE grepl("is not", "This is grepl test") [1] FALSE 
+2
source share

All Articles