r - 如何在 R 中循环多个数据框以使用每个客户一个 Excel 文件创建多选项卡 Excel 输出

标签 r

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

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()

我的迭代尝试是:

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)
}

关于如何实现这一目标有什么想法吗?在这个简单的示例中,我的预期输出是 4 个单独的 xlsx 文件(每个 cust 1 个),每个 xlsx 文件中标记为 tab1 和 tab2 的 2 个选项卡,以及根据迭代中的 cust 命名的 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 中循环多个数据框以使用每个客户一个 Excel 文件创建多选项卡 Excel 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75994921/

相关文章:

r - 如何在 R 中生成变量之间具有循环和 w 依赖关系的多元数据

r - 跨数据框将李克特数据转换为数字

c++ - R 包开发中加载时设置的正确做法

r - 将 sapply/vapply 用于 read_html

r - 如何在不指定x轴的情况下绘制箱形图?

r - 在 R 公式中使用带有特殊字符的列

r - 将 R 文件转换为缺少字符串值的 Stata

r - 在 R 中的数据框的每一行中保留唯一分数

r - 在 Shiny 中单击更改图

r - 自定义函数,ggplot和返回值