Search code examples
rexport-to-excel

R Export several dataframes to differeny Excel files


I have sveral dataframes (mydf1, mydf2, mydf3 etc.). How can I export each dataframe to the separate Excel file so that the name of the file is the name of the dataframe (eg. mydf1.xlsx).

I've tried to put them in a list and do a loop as below. It nearly gives me what I want, but I don't know how to make R name the Excel files properly instead of 1.xlsx, 2.xlsx etc. Any ideas?

install.packages("writexl")
library(writexl)

list_of_dfs <- lapply(ls(pattern="mydf"), function(x) get(x))

for (i in c(1:length(list_of_dfs))){
     write_xlsx(list_of_dfs[i], paste(i,".xlsx"))
   }

Solution

  • Try the following.

    1. use mget to get all df's in one go, no need for lapply;
    2. the list of df's is a named list and the names can be used to assemble the filenames.

    The code corrected is then:

    library(writexl)
    
    list_of_dfs <- mget(ls(pattern = "mydf"))
    
    for(i in seq_along(list_of_dfs)){
      filename <- paste0(names(list_of_dfs)[i], ".xlsx")
      write_xlsx(list_of_dfs[[i]], filename)
    }