繁体   English   中英

如何使用 R purrr 组合数百个 Excel 文件/工作表

[英]How to use R purrr to combine hundreds of Excel files/sheets

我有数百个 Excel 文件,其中包含不同数量的工作表。 我想将所有这些 Excel 文件和工作表合并到一个数据框中。 幸运的是,所有的工作表都采用相同的格式(它们是由客户填写并上传到中央存储库的模板)。

让我们用下面的代码模拟这些 Excel 文件和工作表:

library(tidyverse)
library(openxlsx)
library(readxl)
write.xlsx(list(iris, iris * 2, iris * 3), "three_sheets.xlsx")
write.xlsx(list(iris, iris / 2), "two_sheets.xlsx")

我将如何使用 R purrr 将这些文件和工作表合并到一个数据框中? 我可以改变一列来识别每行来自哪个文件/工作表吗? 如果 purrr 不是此类问题的最佳选择,请随时指出其他解决方案。

purrr似乎是此类操作的不错选择。 你可以做 :

library(readxl)
library(purrr)

#Get full path of all excel files in the folder
all_files <- list.files('path/of/folder',pattern = '\\.xlsx$', full.names = TRUE)
For each file
result <- map_df(all_files, function(x) {
             #Get all the sheet names
             all_sheets <- excel_sheets(x)  
             #read the excel file with one sheet at a time
             map_df(all_sheets, ~read_excel(x, sheet = .x) %>% 
                       #add columns for filename and sheetname
                       dplyr::mutate(filename = basename(x), sheetname = .x))
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM