Search code examples
rexport-to-csvexport-to-excel

Export List of Lists as CSV into seperate Files or Excel Sheets


I have a list of lists mylists with data.table objects

x <- rep("example",5)
y <- 1:5
list1 <- list('a'= data.table(x,y),'b' = data.table(x,y))
list2 <- list('c'= data.table(x,y), 'd' = data.table(x,y))
mylists <- list('Output1'= list1,'Output2' =list2)
mylists

I want to export every object of every list as a separate CSV File (preferably using fwrite from data.table) named like the object i.e. Output1_a.csv

I cannot rbind to one data.frame/table as the data needs to be kept separate.

I've tried using lapply(mylists,fwrite) but have trouble producing separate files with different names.

Additionally how could I produce an xlsx File where all objects of mylists are stored into separate sheets named as described above.

I'd like to know both ways as this might be useful for the future.


Solution

  • for the xlsx version you could do something like this

    x <- rep("example",5)
    y <- 1:5
    list1 <- list('a'= data.table(x,y),'b' = data.table(x,y))
    list2 <- list('c'= data.table(x,y), 'd' = data.table(x,y))
    mylists <- list('Output1'= list1,'Output2' =list2)
    purrr::walk(names(mylists), 
                function(x){
                   writexl::write_xlsx(mylists[[x]], 
                                       path = paste0(x, ".xlsx"))
                })
    

    this will produce xlsx files with the names of the outer list and sheets with the name of the inner lists

    for the csv would I do something like this to first flatten the list

    mylists_flat <- unlist(mylists, recursive = FALSE)
    walk(names(mylists_flat), 
         function(x){
           write.csv(mylists_flat[[x]], 
                     file = paste0(x, ".csv"))
         })
    

    this should produce csv files with the name <outerlist_name>.<innerlist_name>.csv