我有几个数据框,每个数据框都将使用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文件.
先谢谢你.