0

我有数据框并创建了它的一个子集。我通过变量因子拆分数据框及其子集。我想将它保存在excel文件中。我想编写一个循环来创建多个 excel 文件数据框和子集文件,这些文件由变量因子组成。

我写了一个代码,它只是保存了最后一种变量工作簿。如何创建所有工作簿。

rm(list = ls())

mtcars


split_mtcars <- split(mtcars, mtcars$cyl)
split_mtcars_subset <- split(mtcars[,2:4], mtcars$cyl)

cyl_type <- names(split_mtcars)


for(i in length(cyl_type)){
wb <- createWorkbook()
addWorksheet(wb, "raw")
addWorksheet(wb, "subset")

writeData(wb, 1, split_mtcars[[i]])
writeData(wb, 2, split_mtcars_subset[[i]])

saveWorkbook(wb, file = paste0(cyl_type[i],".xlsx"), overwrite = TRUE)
}

提前致谢

4

1 回答 1

0

考虑by按因子拆分数据帧,以避免需要中间对象并隐藏循环。下面输出您的工作簿并构建数据框列表。

split_mtcars <- by(mtcars, mtcars$cyl, function(sub) {
    wb <- createWorkbook()
    addWorksheet(wb, "raw")
    addWorksheet(wb, "subset")

    writeData(wb, 1, sub)
    writeData(wb, 2, sub[,2:5])

    saveWorkbook(wb, file = paste0(sub$cyl[1],".xlsx"), overwrite = TRUE)

    return(sub)   # TO REPLICATE split()
})
于 2019-02-16T01:14:31.270 回答