R List – Check if Item is Present

To check if specific item is present in a given list in R language, use %in% operator. %in% operator returns TRUE if the item is present in the given list, 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 list.

Syntax

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

item %in% x

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

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

ADVERTISEMENT

Examples

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

example.R

x <- list("a", "e", "i", "o", "u")
item <- "e"

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

Output

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

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

example.R

x <- list("a", "e", "i", "o", "u")
item <- "m"

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

Output

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

Conclusion

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