tora0515
tora0515

Reputation: 2547

write list of dataframes to multiple excel files

I have a list of dataframes. Conveniently named:

list.df

and the objects, which are dataframes, are just this:

list.df[[1]]  
list.df[[2]]  
list.df[[3]]

I am trying to use lapply to write each of the list.df objects to a seperate excel sheet.

I can't use the xlsx library because my workplace disables everything Java... so I've been trying write_xlsx.

I've tried the following:

lapply(names(list.df), 
              function (x) write_xlsx(list.df[[x]], file=paste(x, "xlsx", sep=".")))

But nothing happens.

Any help would be appreciated.

Upvotes: 1

Views: 847

Answers (2)

akrun
akrun

Reputation: 887891

For write_xlsx from writexl, there is no file argument. It is the path argument

library(writexl)
lapply(names(list.df), 
          function (x) write_xlsx(list.df[[x]], path=paste(x, "xlsx", sep=".")))

-output directory with files

enter image description here

data

list.df <-  list(A = structure(list(X1 = c("a", "d", "g", "j"), X2 = 1:4, 
    X3 = c("b", "e", "h", "k"), X4 = c("c", "f", "i", "l")),
  class = "data.frame", row.names = c(NA, 
-4L)), B = structure(list(X1 = c("a", "d", "g", "j"), X2 = c(1L, 
2L, 2L, 3L), X3 = c("b", "e", "h", "k"), X4 = c("c", "f", "i", 
"l")), class = "data.frame", row.names = c(NA, -4L)), C = structure(list(
    X1 = c("a", "d", "g", "j"), X2 = 1:4, X3 = c("b", "e", "h", 
    "k"), X4 = c("c", "f", "i", "l")), class = "data.frame", row.names = c(NA, 
-4L)))

Upvotes: 4

Hunaidkhan
Hunaidkhan

Reputation: 1443

i think this might help you

require(openxlsx)
available_dfs<- ls()[sapply(ls(), function(x) is.data.frame(get(x)))]

list_of_datasets <- list("Name of DataSheet1" = dataframe1, "Name of Datasheet2" = dataframe2)
write.xlsx(list_of_datasets, file = "writeXLSX2.xlsx")

Upvotes: 4

Related Questions