gpt4 book ai didi

r - 如何将一个数据框逐行拆分成多个数据框,然后导出到excel? R

转载 作者:行者123 更新时间:2023-12-04 03:49:05 25 4
gpt4 key购买 nike

这是我正在处理的数据

Sales <- data.frame(State  = c("New York", "New Jersey", "Texas","New Mexico","California",
"Kansas","Florida","Alaska","Montana", "Maine"),

Units = c(455,453,125,135,135,568,451,125,215,314),

Sales = c("20000","12530","51110","54110","65000",
"58220","54612","45102","45896","12510"),

ManagerName = c("Chip","Kelly","Steve","Young","Troy",
"Aikman", "Chad","Pennington","Mike","Vick")

)

我的最终目标是为每个“州”创建 10 个不同的 excel 文件。

我知道我可以做类似的事情

#Seperate by State
library(dplyr)
NewYork <- Sales %>% filter(State == "New York")

#Save to excel
library(xlsx)
write.xlsx(NewYork, file="NewYork-Sales-November2020.xlsx",
sheetName="NewYork")

但问题是我有超过 50 行并且不希望有 50 个命令来按状态过滤,然后再有 50 个命令来编写 excel 文件。

有没有更有效的方法将每一行“状态”保存到不同的 excel 文件中?

最佳答案

以下是问题要求的,我已经用发布的数据对其进行了测试。

  1. split数据由 State ;
  2. 创建工作簿;
  3. 将工作表添加到工作簿;
  4. 将每个子data.frame写入工作簿;
  5. 将所有内容保存到磁盘。

工作表由 State 命名.

library(openxlsx)

sp <- split(Sales, Sales$State)
names(sp) <- ifelse(nchar(names(sp)) > 31, substr(names(sp), 1, 31), names(sp))
wb <- createWorkbook(creator = "FruityPebblePug")
lapply(seq_along(sp), function(i){
addWorksheet(wb, sheetName = names(sp)[[i]])
})
lapply(seq_along(sp), function(i){
writeData(wb, sheet = names(sp)[[i]], sp[[i]])
})
saveWorkbook(wb, "Sales-November2020.xlsx")

comments 中所述, 如果工作表名称有太多字符,超出 Excel 的 31 个字符限制,以下将工作表命名为 "State 1" , "State 2"

sp <- split(Sales, Sales$State)
wb <- createWorkbook(creator = "FruityPebblePug")
lapply(seq_along(sp), function(i){
addWorksheet(wb, sheetName = paste("State", i))
})
lapply(seq_along(sp), function(i){
writeData(wb, sheet = paste("State", i), sp[[i]])
})
saveWorkbook(wb, "Sales-November2020_b.xlsx")

关于r - 如何将一个数据框逐行拆分成多个数据框,然后导出到excel? R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64701971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com