Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

in
r
list
communitycreator

How to check if an item exists in a list in R

Onyejiaku Theophilus Chidalu

Overview

In R, a list is a collection of ordered and changeable data.

To create a list object in R, we use the list() function. The list() function takes the items that we want to arrange into a list as its parameter value.

Now, let’s create a list with the help of the list() function:

# list containing numerical values
numbers_list <- list("1, 2, 3, 4, 5")

# list containing string values
fruits_list <- list("oranges", "bananas", "pears")

# printing our lists
numbers_list

fruits_list

Code explanation

  • Line 2: We create a list called numbers_list, which contains numerical values as its items.

  • Line 5: We create another list called fruits_list, which contains strings as its items.

  • Lines 8–9: We print our lists.

Checking if an item exists in a list

Interestingly, we can find out if a given element is present in a list we created. To do this, we use the %in% operator.

The %in% operator returns True if the specified element is present in the list. Otherwise, it returns False. Now, let’s demonstrate this with code:

# creating a list
my_fruits_list <- list("oranges", "bananas", "pears")

# is oranges in the list? True
"oranges" %in% my_fruits_list

# is apples in the list? False
"apple" %in% my_fruits_list
Implementing the "%in%" operator to check for the existence of an item in a list

Code explanation

  • Line 2: We create a list called my_fruits_list.

  • Line 5: We check if the item or string "oranges" is present in the my_fruits_list list, using the %in% operator, .

  • Line 8: We check if the item or string "apple" is present in the my_fruits_list list, using the %in% operator.

RELATED TAGS

in
r
list
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring