【问题标题】:Importing a list of excel files in R by sheet names containing a specific string通过包含特定字符串的工作表名称在 R 中导入 excel 文件列表
【发布时间】:2021-01-09 01:08:16
【问题描述】:

我有 36 个 excel 文件,只需将每个文件中的一张读入数据框。工作表名称并不完全相同,但它们共享一个公共字符串(例如,“Expense Audit”、“Jan Expense Audit”、“19 Expense Audit”)。我想为 list.files 编写一个函数,然后使用 read_excel 仅将包含“Expense Audit”字符串的工作表拉入单个数据框。

【问题讨论】:

  • 我认为在阅读 Excel 之前学习工作表名称会很棘手。有不同的包允许您读取 excel 文件,然后解析对象的名称。最耗时的部分可能是一开始就读入excel文件。获得名称后,您可以使用grepl 或其他函数对所需的工作表进行子集化,然后继续将工作表组合成一个对象。这有帮助吗?

标签: r tidyverse


【解决方案1】:

你可以试试:

library(purrr)
library(readxl)

#List all the excel files
file_path <- list.files(path = '/path/to/excel/files/', pattern = '\\.xlsx$', full.names = TRUE)

#Read each excel file and combine them in one dataframe
map_df(file_path, ~{
  #get all the names of the sheet
  sheets <- excel_sheets(.x)
  #Select the one which has 'Expense Audit' in them
  sheet_name <- grep('Expense Audit', sheets, value = TRUE)
  #Read the excel with the sheet name
  read_excel(.x, sheet_name)
}) -> data

data

【讨论】:

  • 这正是我想要的方法。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多