How To Check If One or More Elements is in a Vector

In this tutorial, we will learn about is.element() function available in base R and use it to check if one or more elements is present in a vector.

Let us create a sample vector in R

example_vector <- c(1, 2, 3, 4, 7, 8)

Our simple vector hs 6 elements.

example_vector
## [1] 1 2 3 4 7 8

If we want to check if a value us present in the vector, we can use is.element() function available in base R using the format

is.element(value, example_vector)

And if the vector contains the value, we get TRUE as a result and FALSE as result if the vector does not contain the value.

In our toy example, if we check if value 1 is in the vector, we will get TRUE as result.

is.element(1, example_vector)
## [1] TRUE

If we test for a value that is not present in the vector, we will get FALSE as result.

is.element(10, example_vector)
## [1] FALSE

We can use is.element() function to test of multiple values are present in the vector of interest. Here, we ask if the vector contains values 1 and 2. And since both the values are present, we get a vector with two TRUE values.

is.element(1:2, example_vector)

## [1] TRUE TRUE

If we test multiple values present in the vector, where some are present and others are not, we get a boolean vector with TRUE/FALSE.

For example, here we ask if the vector contains values 1 and 10. Since the value 1 is present in the vector, we get

is.element(c(1,10), example_vector)

## [1]  TRUE FALSE

In addition to is.element() function, we can also use %in% operator to test if one or more elements in a vector. %in% operator has the same functionality

c(10,1) %in% example_vector

## [1] FALSE  TRUE

Here are some other examples.

1 %in% example_vector
## [1] TRUE
1:2 %in% example_vector
## [1] TRUE TRUE
Exit mobile version