我有几个数据框,每个数据框都将使用Openxlsx填充一个特定的选项卡.在每个数据帧中有多个客户.为了自动生成文件,我想迭valet 户列表并将适当的数据框写入预定义的选项卡名,一旦该客户的所有选项卡都完成后,将整个xlsx文件写入驱动器,根据客户名称命名文件,然后移动到下一个迭代(Customer).我已经使用以下示例数据设置并try 执行此操作:

library(tidyverse)
library(openxlsx)

df.1 <- tribble(
  ~customer  ,~period, ~cost1, ~cost2 ,
  'cust1',  '202201', 5, 10,
  'cust1',  '202202', 5, 10,
  'cust1',  '202203', 5, 10,
  'cust1',  '202204', 5, 10,
  'cust2',  '202203', 5, 10,
  'cust2',  '202204', 5, 10,
  'cust2',  '202202', 5, 10,
  'cust3',  '202204', 5, 10,
  
)

df.2 <- tribble(
  ~customer  ,~period, ~cost3,
  'cust1',  '202201', 5,
  'cust1',  '202202', 5,
  'cust1',  '202203', 5,
  'cust1',  '202204', 5,
  'cust2',  '202203', 5,
  'cust3',  '202203', 5,
  'cust3',  '202204', 5,
  'cust4',  '202201', 5,
)

df.1_cust <- df.1 %>% select(customer) %>% distinct()
df.2_cust <- df.2 %>% select(customer) %>% distinct()

cust_list <- df.1_cust %>% 
  rbind(df.2_cust) %>% 
  distinct()

我在迭代中的try 是:

tab1_data <- df.1 # the data that will go into tab 1
tab2_data <- df.2  # the data that will go into tab 2


for (i in 1:length(cust_list)) {
wb <- openxlsx::createWorkbook()
openxlsx::addWorksheet(wb, 'tab1')
openxlsx::addWorksheet(wb, 'tab2')

openxlsx::writeData(tab1, startCol = 1, startRow = 1,x = tab1_data[i])
openxlsx::writeData(tab2, startCol = 1, startRow = 1,x = tab2_data[i])

openxlsx::saveWorkbook(wb, overwrite = T)
}

有什么 idea 可以让我实现这个目标吗?在这个简单的例子中,我的预期输出是4个单独的xlsx文件(每个客户1个),每个xlsx文件中有2个标签,分别标记为tab1和tab2,以及根据迭代中的客户命名的xlsx文件.

先谢谢你.

推荐答案

考虑到您的数据集,我可能会这样做

library(openxlsx)
library(dplyr)
#listing customer names
cust_list <- unique(c(df.1$customer, df.2$customer))
#looping over customer names
for (i in 1:length(cust_list)) {
  #fitler data for tab 1 and tab 2 based on customer name
  tab1_data <- filter(df.1, customer==cust_list[i]) # the data that will go into tab 1
  tab2_data <- filter(df.2, customer==cust_list[i]) # the data that will go into tab 2
  #create workbook
  wb <- createWorkbook()
  #add worksheet
  addWorksheet(wb, 'tab1')
  addWorksheet(wb, 'tab2')
  #fill the worksheets
  writeData(wb, 'tab1', startCol = 1, startRow = 1,x = tab1_data)
  writeData(wb, 'tab2', startCol = 1, startRow = 1,x = tab2_data)
  #write out to excel files
  saveWorkbook(wb, paste0('file_', cust_list[i], '.xlsx'), overwrite = T)
}

R相关问答推荐

如何使用行政边界形状文件中的人口普查数据调整格栅数据集中的人口数据

在R中列表的结尾添加数字载体

找出疾病消失的受试者

如何使用R中的dhrr函数将李克特量表的因子列从长转换为宽?

如何求解arg必须为NULL或deSolve包的ode函数中的字符向量错误

使用tidyverse方法绑定行并从一组管道列表执行左连接

如何在R中合并和合并多个rabrame?

如何直接从Fortran到R的数组大小?

根据多个条件增加y轴高度以适应geom_text标签

提取具有连续零值的行,如果它们前面有R中的有效值

移除仪表板Quarto中顶盖和车身之间的白色区域

将文件保存到新文件夹时,切换r设置以不必创建目录

R-按最接近午夜的时间进行筛选

R:如果为NA,则根据条件,使用列名模式将缺少的值替换为另一列中的值

R中的类别比较

R+reprex:在呈现R标记文件时创建可重现的示例

自动STAT_SUMMARY统计与手动标准误差之间的差异

如何删除设置大小的曲线图并添加条形图顶部数字的百分比

我需要使用ggplot2制作堆叠条形图

重写时间间隔模糊连接以减少内存消耗