Test if a vector contains a given element

后端 未结 7 1391
慢半拍i
慢半拍i 2020-11-22 02:40

How to check if a vector contains a given value?

7条回答
  •  再見小時候
    2020-11-22 02:54

    I really like grep() and grepl() for this purpose.

    grep() returns a vector of integers, which indicate where matches are.

    yo <- c("a", "a", "b", "b", "c", "c")
    
    grep("b", yo)
    [1] 3 4
    

    grepl() returns a logical vector, with "TRUE" at the location of matches.

    yo <- c("a", "a", "b", "b", "c", "c")
    
    grepl("b", yo)
    [1] FALSE FALSE  TRUE  TRUE FALSE FALSE
    

    These functions are case-sensitive.

提交回复
热议问题