我有数百个中等大小的Excel文件(5000到50万行,大约100列),需要加载到R中。 这些文件具有明确定义的命名模式,例如x_1.xlsx
,x_2.xlsx
等。
如何以最快、最直接的方式将这些文件加载到R中?
list.files
函数可以创建一个包含工作目录中所有文件名的列表。接下来,您可以使用lapply
函数循环遍历该列表,并使用readxl
软件包中的read_excel
函数读取每个文件。请注意保留HTML标签。library(readxl)
file.list <- list.files(pattern='*.xlsx')
df.list <- lapply(file.list, read_excel)
这种方法当然也可以与其他文件读取函数一起使用,例如 read.csv
或 read.table
。只需将 read_excel
替换为适当的文件读取函数,并确保在 list.files
中使用正确的模式。
如果您还想包括子目录中的文件,请使用:
file.list <- list.files(pattern='*.xlsx', recursive = TRUE)
读取Excel文件的其他可能包括:openxlsx和xlsx
bind_rows
将它们绑定到一个数据框中:library(dplyr)
df <- bind_rows(df.list, .id = "id")
rbindlist
:library(data.table)
df <- rbindlist(df.list, idcol = "id")
两者都可以选择添加一个id
列来标识不同的数据集。
更新:如果您不想使用数字标识符,只需在sapply
中使用simplify = FALSE
读取file.list
中的文件:
df.list <- sapply(file.list, read.csv, simplify=FALSE)
bind_rows
或 data.table 中的 rbindlist
时,id
列现在包含文件名。purrr
包中的另一种方法:library(purrr)
file.list <- list.files(pattern='*.csv')
file.list <- setNames(file.list, file.list) # only needed when you need an id-column with the file-names
df <- map_df(file.list, read.csv, .id = "id")
获取命名列表的其他方法:如果您不仅想要数字标识符,那么在将它们绑定在一起之前,可以将文件名分配给列表中的数据框。有几种方法可以做到这一点:
# with the 'attr' function from base R
attr(df.list, "names") <- file.list
# with the 'names' function from base R
names(df.list) <- file.list
# with the 'setattr' function from the 'data.table' package
setattr(df.list, "names", file.list)
rbindlist
或dplyr中的bind_rows
将数据框列表绑定在一起成为一个数据框。其中id
列现在将包含文件名而不是数字标识符。
read.xlsx
可能会慢一些,但这是一个你可以并行运行的过程,只要所有核心都在本地机器上(或者有访问相同共享目录的权限)。这至少可以弥补一些时间损失。注意:我以前没有尝试过并行读取文件,但我认为它应该可以工作——只要所有核心都在同一台机器上。 - Benjaminopenxlsx
包中的read.xlsx
函数,而不是xlsx
包中的read.xlsx
函数。 - Jaap