如何解决如何使用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))
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。