rlistlabeling

How to name a list object in R


In R the objects of the list itself [1], [2] and [[3]] can't seem to be renamed. See:

my_df1 <- mtcars[1:10,]
my_df1 <- mtcars[11:20,]
my_df1 <- mtcars[21:30,]
my_list <- list(my_df1, my_df2, my_df3)

This gives me the following: enter image description here

Is there a way to rename the [1] objects themselves? I find this a drawback of R. I am dealing with categories of data and want to be sure which category I am dealing with by labelling each object. Thanks


Solution

  • If you want to name the lists while creating them you can use tibble::lst

    my_df1 <- mtcars[1:10,]
    my_df2 <- mtcars[11:20,]
    my_df3 <- mtcars[21:30,]
    my_list <- tibble::lst(my_df1, my_df2, my_df3)
    

    If the list is already created you can use names or setNames to name the list.

    names(my_list) <- c('list1', 'list2', 'list3')
    
    setNames(my_list, c('list1', 'list2', 'list3'))