Extract List Elements Conditionally in R (Example)
This page shows how to subset list elements based on a condition in R.
The tutorial is structured as follows:
Let’s jump right to the example:
Construction of Example Data
Consider the following example data:
my_list <- list(A = 1:5, # Create example list B = letters[7:1], C = "X", D = 10:13) my_list # Print example list # $A # [1] 1 2 3 4 5 # # $B # [1] "g" "f" "e" "d" "c" "b" "a" # # $C # [1] "X" # # $D # [1] 10 11 12 13
Have a look at the previously shown output of the RStudio console. It visualizes that our example data is a list with four different list elements.
Example: Conditionally Subset List Using Filter() Function
This section shows how to extract specific list elements conditionally.
Let’s assume that we want to get a new list containing only list elements that have the character class.
For this task, we can use the Filter function as shown below:
Filter(function(x) is.character(x), my_list) # Applying Filter function # $B # [1] "g" "f" "e" "d" "c" "b" "a" # # $C # [1] "X"
As you can see based on the previous output, we have returned a new list containing only the list elements B and C, i.e. the character strings.
Video & Further Resources
Do you need further info on the topics of this article? Then I recommend having a look at the following video of my YouTube channel. In the video, I’m illustrating the R code of this post:
Furthermore, you might want to read the other posts of my website. I have released several articles about lists already.
- Select Multiple Elements from List
- How to Add New Elements to a List
- Count Number of List Elements
- Convert Data Frame Columns to List Elements
- Extract Names of List Elements
- Introduction to R Programming
In summary: In this R programming article you have learned how to select certain elements of a list using a logical condition. In case you have any further comments or questions, please let me know in the comments section.
2 Comments. Leave new
Love your R videos. Focused, concise, well-structured, short, and above all, practically useful! Great work! Well done! Many thanks!
Hey Jack,
Thank you so much for the wonderful feedback, glad you find my videos helpful! 🙂
Regards,
Joachim