Reputation: 1769
Making a list of data frames is easy:
d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))
d2 <- data.frame(y1 = c(3, 2), y2 = c(6, 5))
my.list <- list(d1, d2)
My question is: how could I write my.list
on a excel
file, whose sheet are d1
and d2
?
Upvotes: 1
Views: 401
Reputation: 35604
Use write.xlsx
in openxlsx
. It can take a list of multiple data frames as input and turn each data frame into an individual sheet of the final excel file.
library(openxlsx)
write.xlsx(my.list, "foo.xlsx", sheetName = c("d1", "d2"))
If your list has been named, i.e. names(my.list)
is not NULL
, then you can neglect the argument sheetName
and the sheet names will be set as the list names by default.
Upvotes: 5
Reputation: 689
Using xlsx
package:
library(xlsx)
wb <- createWorkbook()
sheet1 <- createSheet(wb,"d1")
sheet2 <- createSheet(wb,"d2")
addDataFrame(my.list[[1]],
sheet=sheet1,
startRow=1,
row.names=FALSE)
addDataFrame(my.list[[2]],
sheet=sheet2,
startRow=1,
row.names=FALSE)
saveWorkbook(wb,file = "myXlsx.xlsx")
Generic way:
sheetNames<-c("d1","d2")
library(xlsx)
wb <- createWorkbook()
for(i in 1:length(my.list)){
sheetName<- createSheet(wb,sheetNames[i]) #add sheets to excel
addDataFrame(my.list[[i]],
sheet=sheetName,
startRow=1,
row.names=FALSE)#assign dataframe to sheet
}
saveWorkbook(wb,file = "myXlsx1.xlsx")
Upvotes: 1