首页 > 解决方案 > 如何创建多个工作簿,每个工作簿中有多个工作表

问题描述

我有创建多个 excel 文件的代码。这是一种修改它的方法,以便我可以一次创建多个工作簿,然后我可以将它们写入具有相同名称的 excel 中?

我的代码是:

library(tidyverse)
library(writexl)

lst1 <- list(data1 = mpg, data2 = mpg, data3 = mpg, `data4` = mpg)


IDlist <- mpg %>% pull(cyl) %>% unique

make_one_xlsx <- function(this_id){
    lst1 %>% map(~filter(., cyl == this_id)) %>% write_xlsx(paste0("ID_", this_id, ".xlsx"))
}

IDlist %>% map(make_one_xlsx)

标签: r

解决方案


假设您write_xlsx()readxl包中使用,您可以将数据框列表作为第一个参数传递,这会将每个数据框创建为自己的工作表。该函数还将使用该列表的名称作为 Excel 显示工作表名称。

library(tidyverse)
library(writexl)

# with with some number of data frames
lst1 <- list(data1 = mpg, data2 = mpg, data3 = mpg, `data4` = mpg)

IDlist <- mpg %>% pull(cyl) %>% unique

make_one_xlsx <- function(this_id){
  # make an interim list full of the filtered data
  temp <- lst1 %>% map(~filter(.,cyl == this_id))
  # calculate the summary information and add it to the interim list
  # I have no idea what summary info you need, this is a placeholder
  temp[['Summary']] <- temp %>% map(~summarise_all(.,mean)) %>% bind_rows()
  # write list of data to Excel, the summary table is there now.
  write_xlsx(temp, paste0("ID_", this_id, ".xlsx"))
}

IDlist %>% map(make_one_xlsx)

现在,您可以使用所需的所有选项卡从头开始创建 Excel 文件。


推荐阅读