Test If List Element Exists in R (3 Examples)
In this article, I’ll show how to check whether a list element exists in R programming.
Table of contents:
- Creation of Example Data
- Example 1: Test If List Element Exists with %in%-Operator
- Example 2: Test If List Element Exists with is.null Function
- Example 3: Test If List Element Exists with exists Function
- Video & Further Resources
Here’s the step-by-step process:
Creation of Example Data
In this R programming tutorial, I’ll show you three examples. All of these examples are based on the following list:
my_list <- list(numbers = 1:5, # Create example list letters = letters[1:8], triple_x = "XXX") my_list # Print example list # $numbers #  1 2 3 4 5 # # $letters #  "a" "b" "c" "d" "e" "f" "g" "h" # # $triple_x #  "XXX"
Our list consists of three list elements with the names “numbers”, “letters”, and “triple_x”.
Example 1: Test If List Element Exists with %in%-Operator
In Example 1, you’ll learn how to test whether a list element exists based on the %in%-operator. The following code returns the logical value TRUE, in case the list element “numbers” exists:
"numbers" %in% names(my_list) # %in%-Operator # TRUE
As we already knew, this element exists. Let’s apply the same code to a list element that does not exist:
"something_else" %in% names(my_list) # FALSE
As you can see, the RStudio console returns FALSE.
Example 2: Test If List Element Exists with is.null Function
Another alternative for checking whether a list element exists is provided by the is.null function. As in Example 1, the following R syntax returns TRUE in case the element “numbers” is part of our example list:
!is.null(my_list[["numbers"]]) # is.null function # TRUE
Example 3: Test If List Element Exists with exists Function
A third alternative is provided by the exists function of the R programming language. Have a look at the following R code:
exists("numbers", my_list) # exists function # TRUE
As you can see, the previous R syntax also returns the logical value TRUE.
Video & Further Resources
Have a look at the following video of my YouTube channel. In the video, I’m explaining the R programming codes of this page in a live session.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you may read the other articles of this homepage:
Summary: This article explained how to investigate whether a list value is existing in R. In case you have any further questions, don’t hesitate to let me know in the comments. In addition, please subscribe to my email newsletter to get updates on the newest tutorials.
Statistics Globe Newsletter