Test if a vector contains a given element Test if a vector contains a given element r r

Test if a vector contains a given element


Both the match() (returns the first appearance) and %in% (returns a Boolean) functions are designed for this.

v <- c('a','b','c','e')'b' %in% v## returns TRUEmatch('b',v)## returns the first location of 'b', in this case: 2


is.element() makes for more readable code, and is identical to %in%

v <- c('a','b','c','e')is.element('b', v)'b' %in% v## both return TRUEis.element('f', v)'f' %in% v## both return FALSEsubv <- c('a', 'f')subv %in% v## returns a vector TRUE FALSEis.element(subv, v)## returns a vector TRUE FALSE


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