How to Check if a Vector Contains a Given Element in R

In R, you can use the %in% operator to check if a vector contains a given element. The vector is placed on the left side of the operator, and the element to check for is placed on the right side. If the element is present in the vector, the result of the expression will be TRUE, otherwise it will be FALSE.


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 <- c('Andy', 'Bert', 'Chad', 'Doug', 'Bert', 'Frank')

#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 <- c('Andy', 'Bert', 'Chad', 'Doug', 'Bert', 'Frank')

#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 <- c('Andy', 'Bert', 'Chad', 'Doug', 'Bert', 'Frank')

#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 <- c('Andy', 'Bert', 'Chad', 'Doug', 'Bert', 'Frank')

#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 <- c('Andy', 'Bert', 'Chad', 'Doug', 'Bert', 'Frank')

#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.

The following tutorials explain how to perform other common tasks in R:

x