Is there a grep
function in R that returns TRUE
if a pattern is found anywhere in the given character vector and FALSE
otherwise?
possibly a combination of grepl()
and any()
?
like
> 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 a little unclear as to whether you want that last example to return true or not
grepl is what you are looking for
grepl("is", "This is grepl test")
[1] TRUE
grepl("is not", "This is grepl test")
[1] FALSE
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 do this for strings as well
> x<-c("a","b","c","d")
> any(x=="b")
[1] TRUE
> any(x=="e")
[1] FALSE
And it can be convenient when combined with applies:
> 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
Perhaps you're looking for grepl()
?
> grepl("is", c("This", "is", "a", "test", "isn't", "it?"))
[1] TRUE TRUE FALSE FALSE TRUE FALSE
Where the first argument is the pattern you're looking for, the second argument is the vector against which you want to match, and the returned value is a Boolean vector of the same length describing whether or not the pattern was matched to each element.