rdplyrtidyrdata-manipulationtidy

setnames() in a list object in R


I have a list object below and I need to assign each list object with a specific name such as if the object is in the 1st place in my.list, DF.1, if it is in the 10th place, DF.10. Many thanks in advance.

df1 <- data_frame(ID = paste0(LETTERS[1],1:4), valueA = seq(0.1,0.4,0.1), Category= "Apples", valueDEF = seq(0.1,0.4,0.1), valueDEF2 = seq(0.1,0.4,0.1) )
    df2 <- data_frame(ID = paste0(LETTERS[1],5:8), valueB = seq(0.1,0.4,0.1),  Category= "Apples2")
    df3 <- data_frame(ID = paste0(LETTERS[1],9:12), valueC = seq(0.1,0.4,0.1),  Category= "Apples3")
    
    my.list  <- list(df1, df2, df3);my.list 
    
    for(i in 1:length(my.list)){
      my.list[[i]] <-  paste("DF", i, sep = ".")
      #names(my.list) <- setNames(my.list , c('list1', 'list2', 'list3')) ### in forloop 
    }

EXPECTED ANSWER

 names(my.list) 
DF.1, DF.2, DF.3

Solution

  • We can combine paste (create the names) with setNames (assign the names to the list):

    names(my.list) <- paste0("DF.", 1:length(my.list))
    
    names(my.list)
    [1] "DF.1" "DF.2" "DF.3"