Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a vector contains a given element

Tags:

r

r-faq

vector

How to check if a vector contains a given value?

like image 669
medriscoll Avatar asked Jul 23 '09 02:07

medriscoll


People also ask

How do you check if a string is present in a vector C++?

Use find() and find_if() on a vector of strings.

How do you check if a string is present in vector?

The contains() method of Java Vector class is used to check the vector which is in use contains the specified element or not. It returns true if this vector contains the specified element, otherwise returns false.

How do you find the elements in a vector array?

Approach 1: Return index of the element using std::find() std::find() searches for an element equal to the value that is passed as a parameter and returns an iterator pointing to that element in the vector. The parameter passed here is key k, the function call will return an iterator pointing to key k in the vector.


2 Answers

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 
like image 56
medriscoll Avatar answered Sep 20 '22 13:09

medriscoll


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 TRUE  is.element('f', v) 'f' %in% v ## both return FALSE  subv <- c('a', 'f') subv %in% v ## returns a vector TRUE FALSE is.element(subv, v) ## returns a vector TRUE FALSE 
like image 42
Justin Nafe Avatar answered Sep 18 '22 13:09

Justin Nafe