Rename List Elements in R (2 Examples)
In this R programming tutorial you’ll learn how to modify the names of lists.
Table of contents:
Let’s dig in…
Creation of Example Data
We use the following data as basement for this R programming tutorial:
my_list <- list(1:4, # Create example list letters[5:1], "XXX") my_list # Print example list # [] #  1 2 3 4 # # [] #  "e" "d" "c" "b" "a" # # [] #  "XXX"
The previous output of the RStudio console reveals the structure of our example list: It has three list elements without names for the list elements.
We can also double-check that using the names function:
names(my_list) # Check names of example list # NULL
Let’s add some names to our list!
Example 1: Changing Names of All List Elements
This example illustrates how to modify names of all list items. For this, we have to assign a vector of names to our list as shown below:
names(my_list) <- c("Name_1", "Name_2", "Name_3") # Rename list elements my_list # Print updated list # $Name_1 #  1 2 3 4 # # $Name_2 #  "e" "d" "c" "b" "a" # # $Name_3 #  "XXX" #
Have a look at the output of the RStudio console: It shows that the names of our list elements were changed.
Example 2: Changing Name of Only One List Element
Example 2 explains how to adjust the name of only one specific list element:
names(my_list) <- "This is another name" # Rename only one list element my_list # Print updated list # $Name_1 #  1 2 3 4 # # $`This is another name` #  "e" "d" "c" "b" "a" # # $Name_3 #  "XXX" #
Only the second list item name was replaced.
Video & Further Resources
Have a look at the following video of my YouTube channel. I’m explaining the R programming codes of the present article 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 may want to have a look at the other tutorials of this website. I have published numerous tutorials on topics such as extracting data, numeric values, counting, and lists:
- Select Multiple Elements from List
- Count Number of List Elements in R
- How to Add New Elements to a List in R
- All R Programming Examples
In this tutorial, I have explained how to exchange the names of list variables and items in the R programming language. Let me know in the comments section, in case you have additional questions.
2 Comments. Leave new
Leave a Reply Cancel reply
Statistics Globe Newsletter
as always, thank you so much
As always, you are very welcome! Thanks for your positive feedback!