Extract Names of List Elements in R (2 Examples)
In this article you’ll learn how to return the names of list objects in the R programming language.
Table of contents:
If you want to learn more about these topics, keep reading.
Creation of Example Data
In the first place, let’s construct some example data in R:
my_list <- list(obj1 = 1:5, # Create example list obj2 = "XYZ", obj3 = letters[7:4]) my_list # Print example list # $obj1 # [1] 1 2 3 4 5 # # $obj2 # [1] "XYZ" # # $obj3 # [1] "g" "f" "e" "d" #
Have a look at the previous RStudio console output. It shows that our example list consists of three list objects.
Example 1: Return Names of All List Objects
This example illustrates how to extract the names of all list elements in R.
For this, we can use the names function as shown below:
names(my_list) # Extract all list names # [1] "obj1" "obj2" "obj3"
After running the previous R code, the RStudio console returns the names of our three list elements, i.e. obj1, obj2, and obj3.
Example 2: Return Names of One Specific List Object
In this example, I’ll illustrate how to get the name of one particular list element.
For this, we can subset the output of the names function. In this example, we’ll extract the name of the second list element:
names(my_list)[2] # Extract name of specific element # [1] "obj2"
The name of the second list object is obj2.
Video & Further Resources
Do you want to learn more about lists in R? Then you might watch the following video which I have published on my YouTube channel. I illustrate the examples of this tutorial in the video.
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 read some of the other articles of this homepage. A selection of posts on related topics such as extracting data, data conversion, and matrices is listed below:
- List All Column Names But One in R
- How to Add New Elements to a List
- Convert Data Frame Columns to List Elements
- The R Programming Language
In summary: You have learned in this tutorial how to get the names of list elements in R. In case you have additional questions or comments, please let me know in the comments below.
Statistics Globe Newsletter