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



我有数百个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))
})

最新更新