循环在多个 Excel 工作簿中创建多个工作表

Loop to create multiple sheets in multiple Excel workbooks

我有一个包含两个不同组及其值的数据集,如下所示:

example <- data.frame('Group' = c('building 1', 'building 1', 
                                  'building 2', 'building 2'),
                      'Subgroup' = c('Active','Inactive','Active','Inactive'),
                      'Value' = c('abc','def','ghi','jkl'))

我知道我可以使用 lapply 为每个 'building':

输出一个工作簿
buildings <- split(example, example$Group)

lapply(1:length(buildings), 
        function(x) write.xlsx(buildings[[x]], 
                               file = paste0(names(buildings[x]), '.xlsx'), 
                               row.names = FALSE))

同样,下面是基于列在 1 个工作簿中创建多个工作表的代码:

activity <- split(example, example$Subgroup)

lapply(1:length(activity), 
        function(x) write.xlsx(activity[[x]], file = 'All values.xlsx',
                               sheetName = paste0(names(activity[x])), 
                               append = TRUE, row.names = FALSE))

我的问题是,在 R 中有没有一种方法可以将这些组合起来(或者有其他方法)以按组创建单独的工作簿,并按子组创建多个工作表?我想要的是 Building 1 的文件,它有 2 张:Active 和 Inactive。

我修改你的代码如下。由于 openxlsx::write.xlsx() 将自动使用命名列表的名称,例如 activity,作为工作表的名称。您唯一需要做的就是在 lapply() 函数中拆分 buildings

example <- data.frame('Group' = c('building 1', 'building 1', 'building 2', 'building 2'),
                      'Subgroup' = c('Active','Inactive','Active','Inactive'),
                      'Value' = c('abc','def','ghi','jkl'))


buildings <- split(example, example$Group)

lapply(seq_along(buildings), 
       function(x) {
         activity <- split(buildings[[x]], buildings[[x]]$Subgroup)
         openxlsx::write.xlsx(
           activity,
           file = paste0(names(buildings[x]), '.xlsx'),
           row.names = FALSE
         )
       })

您可以将数据拆分为嵌套列表,第一层按 Group 拆分,第二层按 Subgroup 拆分。然后,您可以将它们写入工作簿中,并循环使用单独的工作表。见下文;

library(dplyr)
library(xlsx)

example %>% 
  mutate_if(is.factor, as.character) %>% 
  split(., .$Group) %>% 
  lapply(., function(x) split(x, x$Subgroup)) %>% 
  lapply(., function(dat) 
    lapply(dat, function(dat.sub) 
      write.xlsx(dat.sub, 
                 file = paste0(as.character(unique(dat.sub$Group)), ".xlsx"),
                 sheetName = paste0(as.character(unique(dat.sub$Subgroup))), 
                 append = TRUE, row.names = FALSE)))