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.

 

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.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


2 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top