sje*_*edi 0 split r export-to-excel dataframe openxlsx
假设我在 R 中有以下数据框,并且希望将数据框拆分为按 Fruit 列分类的单独 Excel 工作表
+--------+-------+
| Fruit | Price |
+--------+-------+
| Apple | 12 |
| Apple | 14 |
| Apple | 15 |
| Orange | 2 |
| Orange | 4 |
| Orange | 6 |
| Pear | 3 |
| Pear | 6 |
| Pear | 9 |
+--------+-------+
Run Code Online (Sandbox Code Playgroud)
将数据帧拆分为 3 个单独的数据帧(Apple、Orange 和 Pear)后,我打算将每个数据帧导出到单独的 Excel 工作表(名为 Apple、Orange 和 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)}
Run Code Online (Sandbox Code Playgroud)
有人能帮忙解决这个问题吗?我的实际数据框有超过 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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4079 次 |
| 最近记录: |