R Vector – Check if Item is Present

To check if specific item is present in a given vector in R language, use %in% operator. %in% operator returns TRUE if the item is present in the given vector, or FALSE if not.

In this tutorial, we will learn how to use %in% operator to programmatically determine if a specific element is present in a given vector.

Syntax

The syntax of the expression to check if item item is present in vector x is

</>
Copy
item %in% x

%in% operator takes two operands. Left side operand is the item, and right side operand is the vector.

The above expression returns a logical value: TRUE or FALSE.

Examples

In the following program, we take a vector in x, and check if the item e is present in this vector x. Since, the expression item %in% x returns logical value, we can use this expression as a condition in R If statement.

example.R

</>
Copy
x <- c("a", "e", "i", "o", "u")
item <- "e"

if (item %in% x) {
    print("Item is present in the Vector.")
} else {
    print("Item is not present in the Vector.")
}

Output

[1] "Item is present in the Vector."

Now, let us take an item "m" which is not present in the vector x. %in% operator must return FALSE, because the specified item is not present in the vector.

example.R

</>
Copy
x <- c("a", "e", "i", "o", "u")
item <- "m"

if (item %in% x) {
    print("Item is present in the Vector.")
} else {
    print("Item is not present in the Vector.")
}

Output

[1] "Item is not present in the Vector."

Conclusion

In this R Tutorial, we learned how to check if an item is present in the vector using %in% operator, with the help of examples.