You can use the following methods to check if a vector contains a given element in R:
Method 1: Check if Vector Contains Element
'some_element' %in% my_vector
Method 2: Find Position of First Occurrence of Element
match('some_element', my_vector)
Method 3: Find Position of All Occurrences of Element
which('some_element' == my_vector)
The following examples show how to use each method in practice.
Example 1: Check if Vector Contains Element
The following code shows how to check if ‘Andy’ exists in a given vector:
#create vector my_vector #check if vector contains 'Andy' 'Andy' %in% my_vector [1] TRUE
The output displays TRUE since the element ‘Andy’ does exist in the vector.
However, suppose we check if ‘Arnold’ exists in the vector:
#create vector my_vector #check if vector contains 'Arnold' 'Arnold' %in% my_vector [1] FALSE
The output displays FALSE since the element ‘Arnold’ does not exist in the vector.
Example 2: Find Position of First Occurrence of Element
The following code shows how to find the position of the first occurrence of ‘Bert’ in a given vector:
#create vector my_vector #find first occurrence of 'Bert' match('Bert', my_vector) [1] 2
The output displays 2 since the element ‘Bert’ occurs first in position 2 of the vector.
And the following code shows how to find the position of the first occurrence of ‘Carl’ in the vector:
#create vector my_vector #find first occurrence of 'Carl' match('Carl', my_vector) [1] NA
The output displays NA since the element ‘Carl’ never occurs in the vector.
Example 3: Find Position of All Occurrences of Element
The following code shows how to find all occurrences of ‘Bert’ in a given vector:
#create vector my_vector #find all occurrences of 'Bert' which('Bert' == my_vector) [1] 2 5
The output displays 2 and 5 since these are the positions in the vector where ‘Bert’ occurs.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Filter a Vector in R
How to Remove NA Values from Vector in R
How to Remove Specific Elements from Vector in R