Test if a vector contains a given element

medriscoll picture medriscoll · Jul 23, 2009 · Viewed 722.5k times · Source

How to check if a vector contains a given value?

Answer

medriscoll picture medriscoll · Jul 23, 2009

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 TRUE

match('b',v)
## returns the first location of 'b', in this case: 2