Select Multiple Elements from List in R (Example)

 

This tutorial explains how to use square brackets to extract several list elements in the R programming language.

Table of contents:

You’re here for the answer, so let’s get straight to the example.

 

Creation of Exemplifying Data

The following data is used as basement for this R tutorial:

my_list <- list(letters[1:3],    # Create example list
                555,
                7:3)
my_list                          # Print list
# [[1]]
# [1] "a" "b" "c"
# 
# [[2]]
# [1] 555
# 
# [[3]]
# [1] 7 6 5 4 3

As you can see based on the previous output of the RStudio console, our exemplifying data is a list consisting of three list elements.

 

Example: Returning Several List Elements by Specifying Index Positions in Square Brackets

This Example shows how to use square brackets to select multiple elements from our list in one line of R code. Consider the following syntax:

my_list[c(1, 3)]                 # Subset list
# [[1]]
# [1] "a" "b" "c"
# 
# [[2]]
# [1] 7 6 5 4 3

As you have seen, we have used the c() function and single square brackets (i.e. [ ]) to extract several elements from our list. Within the c() function we specified the index positions of the list elements we wanted to return.

 

Video & Further Resources

Do you need more information on the topics of this tutorial? Then you might have a look at the following video of my YouTube channel. In the video, I illustrate the content of this page in a live session.

 

 

In addition, you could have a look at the other articles which I have published on this website. You can find a selection of articles below.

 

This article illustrated how to subset multiple list elements in the R programming language. If you have further questions, don’t hesitate to let me know in the comments section. Furthermore, don’t forget to subscribe to my email newsletter in order to receive updates on new articles.

 

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.


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