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 # [] #  "a" "b" "c" # # [] #  555 # # [] #  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 # [] #  "a" "b" "c" # # [] #  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.
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.
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.
- Select Only First Element of Nested List
- Extract Just Number from Named Numeric Vector
- Extract Numbers from Character String Vector
- The R Programming Language
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.
Statistics Globe Newsletter