r - 如何创建多个工作簿,每个工作簿中有多个工作表
问题描述
我有创建多个 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)
解决方案
假设您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 文件。
推荐阅读
- java - 使用 LittleProxy 拦截、操作和转发请求
- amazon-web-services - 使用 eventbridge 检测 cloudwatch 日志中的错误
- c# - 将 URL 限制为特定数据库用户名 ASP.NET
- linux - 如何在禁用 SMP 支持的情况下运行“invd”指令?
- java - 如何将子类的字段值与超类字段值一起存储到 ArrayList 中?- 爪哇
- javascript - 以编程方式触发 React-Select 以选择/提交顶部选项?
- string - 为什么我无法重新分配这个基本变量值(GODOT 游戏引擎)
- laravel - 如何混合使用 Laravel 路由和 Vue 路由?
- laravel - ID 为空时如何使用 Laravel 的 updateOrCreate() 方法创建实例?
- r - 如何使用 ggpredict 创建图形