Test if a vector contains a given element

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

How to check if a vector contains a given value?

7条回答
  •  我在风中等你
    2020-11-22 02:44

    I will group the options based on output. Assume the following vector for all the examples.

    v <- c('z', 'a','b','a','e')
    

    For checking presence:

    %in%

    > 'a' %in% v
    [1] TRUE
    

    any()

    > any('a'==v)
    [1] TRUE
    

    is.element()

    > is.element('a', v)
    [1] TRUE
    

    For finding first occurance:

    match()

    > match('a', v)
    [1] 2
    

    For finding all occurances as vector of indices:

    which()

    > which('a' == v)
    [1] 2 4
    

    For finding all occurances as logical vector:

    ==

    > 'a' == v
    [1] FALSE  TRUE FALSE  TRUE FALSE
    

    Edit: Removing grep() and grepl() from the list for reason mentioned in comments

提交回复
热议问题