R:读取多个 excel 个文件,提取前 sheet 个名称,并创建新列

R: reading multiple excel files, extract first sheet names, and create new column

我有多个 excel 文件,它们具有唯一的 sheet 名称(在我的例子中是文件创建日期)。我批量阅读它们,需要将 sheet 名称分配给新列 "id" 中的每个文件。我知道如何制作数字 id,或 id = 文件名,但找不到将 sheet 名称作为 id 的方法。

library(readxl)
library(data.table)

file.list <- list.files("C:/Users/.../Studies/",pattern='*.xlsx')
df.list <- lapply(file.list, read_excel)

#id = numeric
df <- rbindlist(df.list, idcol = "id")

#Or by file name:
attr(df.list, "names") <- file.list
df2 = rbindlist(df.list,idcol="id")

#How to get sheet names?

如果您碰巧只处理文件的前 sheet,那么以下内容应该可以帮助您获取前 sheet 的名称作为 id你的数据框:

attr(df.list, "names") <- sapply(file.list, function(x) excel_sheets(x)[1])

但是,如果您正在考虑从所有可用的 sheet 中导入数据,您将需要做更多的工作,从如何创建数据框列表开始:

df.list <- lapply(file.list,function(x) {
  sheets <- excel_sheets(x)
  dfs <- lapply(sheets, function(y) {
    read_excel(x, sheet = y)
  })
  names(dfs) <- sheets
  dfs
})

这应该创建一个列表列表,其中应该包含文件中的所有可用数据。主列表中的列表以 sheet 名称适当命名。因此,之后您不需要更改任何属性。但是要将数据帧绑定在一起,您需要执行以下操作:

rbindlist(lapply(df.list, rbindlist, id = "id"))

希望这有用。