将R中的列表写入Excel文件

tus*_*haR 0 excel file-io r

我有一个包含5个不同长度数据框的列表。我想将这些数据框写在同一张Excel工作表中。

我已经尝试使用WriteXLS()write.xlsx()但无法获得理想的结果。

dig*_*All 5

这是一个示例,其中xlsx包函数用于在同一张纸上写5个不同的表:

library(xlsx)

### create a sample list
set.seed(123)
theList <- list()

theList$df1 <- data.frame(a=1:5,b=sample(c('X','Y','Z'),5,T))
theList$df2 <- data.frame(a=1:3,b=sample(c('X','Y','Z'),3,T),c=sample(c('A','B','C'),3,T))
theList$df3 <- data.frame(answer=42)
theList$df4 <- data.frame(x=1:2,y=sample(c('I','J','K'),2,T),z='M')
theList$df5 <- data.frame(m=1.2345,n='foo')
###


wb <- createWorkbook()
sheet <- createSheet(wb,"SheetNameHere")

currRow <- 1
for(i in 1:length(theList)){

  cs <- CellStyle(wb) + Font(wb, isBold=TRUE) + Border(position=c("BOTTOM", "LEFT", "TOP", "RIGHT"))

  addDataFrame(theList[[i]],
               sheet=sheet,
               startRow=currRow,
               row.names=FALSE,
               colnamesStyle=cs)

  currRow <- currRow + nrow(theList[[i]]) + 2 
}

saveWorkbook(wb,file = "myXlsx.xlsx")
Run Code Online (Sandbox Code Playgroud)

结果:

Excel快照