Find Elements in List in R (2 Examples)
In this tutorial, I’ll demonstrate how to identify list elements containing particular values in the R programming language.
The table of content is structured like this:
Let’s dive right in!
Example Data
The first step is to create some example data:
my_list <- list(1:5, # Create example list letters[1:5], "a", letters[2:5]) my_list # Print example list # [[1]] # [1] 1 2 3 4 5 # # [[2]] # [1] "a" "b" "c" "d" "e" # # [[3]] # [1] "a" # # [[4]] # [1] "b" "c" "d" "e"
The previous output of the RStudio console shows that our example data is a list with four list elements.
Example 1: Find List Elements that Contain Certain Value
In this section, I’ll show how to identify the index positions of all list elements that contain a particular value.
For this task, we can use the which and sapply functions as shown below:
which(sapply(my_list, function(x) "a" %in% x)) # Index positions of matches # [1] 2 3
The previous R code has returned the values 2 and 3, i.e. the index positions of list elements that contain the letter “a”.
Example 2: Create Subset of List Elements that Contain Certain Value
In this example, I’ll explain how to create a list subset of list elements that contain a certain value.
Have a look at the following R code:
my_list_subset <- my_list[sapply(my_list, function(x) "a" %in% x)] # Subset of list my_list_subset # Print subset # [[1]] # [1] "a" "b" "c" "d" "e" # # [[2]] # [1] "a"
As you can see, we have created a new list that contains only those two list elements that contain the letter “a”.
Video, Further Resources & Summary
Have a look at the following video on my YouTube channel. In the video, I’m explaining the topics of this tutorial in a live session:
In addition to the video, you might read the related articles which I have published on my website. Please find some tutorials on related topics such as extracting data, data inspection, data conversion, and lists below.
- Find Common Elements from Multiple Vectors
- Convert Data Frame Columns to List Elements
- Extract Names of List Elements
- Extract List Elements Conditionally in R
- Introduction to R
In this article you have learned how to find all list elements that contain a specific values in the R programming language. If you have further comments and/or questions, don’t hesitate to tell me about it in the comments.