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

前端 未结 4 1607
醉梦人生
醉梦人生 2020-12-14 21:25

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

相关标签:
4条回答
  • 2020-12-14 21:30

    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

    0 讨论(0)
  • 2020-12-14 21:40

    grepl is what you are looking for

    grepl("is", "This is grepl test")
    [1] TRUE
    grepl("is not", "This is grepl test")
    [1] FALSE
    
    0 讨论(0)
  • 2020-12-14 21:51

    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
    
    0 讨论(0)
  • 2020-12-14 21:55

    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.

    0 讨论(0)
提交回复
热议问题