How to Change Names of List Items in R (2 Examples)
This page shows how to exchange the names of list items in R programming.
Creation of Example Data
example_list <- list(data.frame(x = 1:5, y = 5:1), # Constructing list object LETTERS[15:7], "yayaya") example_list # Showing example list # [[1]] # x y # 1 1 5 # 2 2 4 # 3 3 3 # 4 4 2 # 5 5 1 # # [[2]] # [1] "O" "N" "M" "L" "K" "J" "I" "H" "G" # # [[3]] # [1] "yayaya" # |
example_list <- list(data.frame(x = 1:5, y = 5:1), # Constructing list object LETTERS[15:7], "yayaya") example_list # Showing example list # [[1]] # x y # 1 1 5 # 2 2 4 # 3 3 3 # 4 4 2 # 5 5 1 # # [[2]] # [1] "O" "N" "M" "L" "K" "J" "I" "H" "G" # # [[3]] # [1] "yayaya" #
Example 1: Renaming Name of Each List Element
names(example_list) <- paste0("My_Element_No_", 1:length(example_list)) # Rename list elements example_list # Showing new list # $My_Element_No_1 # x y # 1 1 5 # 2 2 4 # 3 3 3 # 4 4 2 # 5 5 1 # # $My_Element_No_2 # [1] "O" "N" "M" "L" "K" "J" "I" "H" "G" # # $My_Element_No_3 # [1] "yayaya" # |
names(example_list) <- paste0("My_Element_No_", 1:length(example_list)) # Rename list elements example_list # Showing new list # $My_Element_No_1 # x y # 1 1 5 # 2 2 4 # 3 3 3 # 4 4 2 # 5 5 1 # # $My_Element_No_2 # [1] "O" "N" "M" "L" "K" "J" "I" "H" "G" # # $My_Element_No_3 # [1] "yayaya" #
Example 2: Renaming Name of One Specific List Element
names(example_list)[1] <- "AAAAAAAAAAAAA" # Change name of one element example_list # Showing new list # $AAAAAAAAAAAAA # x y # 1 1 5 # 2 2 4 # 3 3 3 # 4 4 2 # 5 5 1 # # $My_Element_No_2 # [1] "O" "N" "M" "L" "K" "J" "I" "H" "G" # # $My_Element_No_3 # [1] "yayaya" # |
names(example_list)[1] <- "AAAAAAAAAAAAA" # Change name of one element example_list # Showing new list # $AAAAAAAAAAAAA # x y # 1 1 5 # 2 2 4 # 3 3 3 # 4 4 2 # 5 5 1 # # $My_Element_No_2 # [1] "O" "N" "M" "L" "K" "J" "I" "H" "G" # # $My_Element_No_3 # [1] "yayaya" #
Related Tutorials
Please have a look at the following R tutorials. They discuss topics such as loops, extracting data, and lists.