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

前端 未结 4 1661
醉梦人生
醉梦人生 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: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
    

提交回复
热议问题