Search code examples
rwritexl

write_xlsx results in error: "Argument x must be a data frame or list of data frames" This despite data being a list of DFs


I need to write an excel file with multiple sheets named "Cases", "Coordinators", "Contacts"

I have checked the class of each--e.g., class(Cases)--and the result in each case is:

class(Cases)
[1] "tbl_df"     "tbl"        "data.frame"

I combine these dfs into a list called "compiledData" as follows:

compiledData <- c(Cases, Coordinators, Contacts)

and checked class of compiledData as follows:

class(compiledData)
[1] "list"

So, I am confused as to why the following code results in the following error:

write_xlsx(compiledData, "FileName.xlsx")
Error in write_xlsx(compiledData, "FileName.xlsx") : 
  Argument x must be a data frame or list of data frames

Any assistance would be greatly appreciated. I have been searching for two days for a solution, but have not found an answer. Apologies in advance if a solution has already been posted and I've not seen it.

One update: I changed compiledData <- c(Cases, Coordinators, Contacts) to: compiledData <- list(Cases, Coordinators, Contacts) and the Excel file is now being created without error. My new problem is that the worksheets in the excel file are not labeled "Cases", "Coordinators", "Contacts"--they are Sheet1, Sheet2, Sheet3


Solution

  • When you store the data frames in a list (ie, compiledData <- list(Cases, Coordinators, Contacts)) the elements are unnamed. For instance, in this example:

    df1 <- df2 <- df3 <- tibble::tibble(A = 1:5, B = 1:5, C = 1:5)
    comb <- list(df1, df2, df3)
    
    names(comb)
    # NULL
    

    To export the to excel with the df names, you just have to name the elements in the list (ie, using names() or setNames()):

    df1 <- df2 <- df3 <- tibble::tibble(A = 1:5, B = 1:5, C = 1:5)
    comb <- list(df1, df2, df3)
    
    names(comb) <- c("df1", "df2", "df3")
    writexl::write_xlsx(comb, "test.xlsx")
    
    # or one-liner
    
    writexl::write_xlsx(setNames(comb, c("df1", "df2", "df3")), "test.xlsx")
    

    Note: since you resolved your initial question (RE: properly exporting) but edited to pose a new one (RE: naming sheets), please edit your question to remove the original question and only focus on the new one. This will help future readers. Good luck!