将R中的大数据帧拆分,并在单个Excel工作簿中将其输出到单独的工作表中



假设我在R中有以下数据帧,并且我希望将数据帧拆分为按Fruit列分类的单独Excel表


+--------+-------+
| Fruit  | Price |
+--------+-------+
| Apple  |    12 |
| Apple  |    14 |
| Apple  |    15 |
| Orange |     2 |
| Orange |     4 |
| Orange |     6 |
| Pear   |     3 |
| Pear   |     6 |
| Pear   |     9 |
+--------+-------+

在将数据帧拆分为3个单独的数据帧(Apple、Orange和Pear(后,我打算将每个数据帧导出到一个单独的Excel表(名为Apple、Oranger和Pear,但存储在同一Excel工作簿Out.xlsx中(。但是,下面的R代码不起作用。输出是一个Excel工作簿Out.xlsx,其中只有一张表Pear,包含Pear数据帧。

library(openxlsx)
df <- read_excel("Export excel test.xlsx")
output <- split(df, df$Fruit)
for (i in 1:length(output)){write.xlsx(x = output[i],
file = "Out.xlsx", sheetName = names(output[i]),append = TRUE)}

有人能帮忙吗?我的实际数据帧有超过400万行,因此我需要将数据帧拆分成单独的表格,以避开Excel的行限制

看起来您正在使用xlsx包中的命令。

xlsx包还提供write.xlsx函数,该函数允许您附加到现有工作簿。

library(xlsx)
write.xlsx(subset(iris, subset=Species=="setosa"), 
file="iris.xlsx", sheetName = "setosa")
write.xlsx(subset(iris, subset=Species=="versicolor"), 
file="iris.xlsx", sheetName = "versicolor", append=TRUE)
write.xlsx(subset(iris, subset=Species=="virginica"), 
file="iris.xlsx", sheetName = "virginica", append=TRUE)

openxlsx软件包的作用略有不同。在这里,我将使用循环。

library(openxlsx)
output <- split(iris, iris$Species)
wb <- createWorkbook()
for (i in 1:length(output)) {
addWorksheet(wb, sheetName=names(output[i]))
writeData(wb, sheet=names(output[i]), x=output[[i]]) # Note [[]]
}
saveWorkbook(wb, "iris.xlsx", overwrite = TRUE)

相关内容

最新更新