如何将多个(excel)文件读入R?

Man*_*l R 31 import excel r

我有上百个中等大小的Excel文件(5000两50.0000行之间有大约100列)加载到R.他们有一个明确的命名模式,比如x_1.xlsx,x_2.xlsx等等.

如何以最快,最直接的方式将这些文件加载​​到R中?

Jaa*_*aap 70

随着list.files你可以创建你workingdirectory所有文件名列表.接下来,您可以使用lapply循环遍历该列表并使用包中的read_excel函数读取每个文件readxl:

library(readxl)
file.list <- list.files(pattern='*.xlsx')
df.list <- lapply(file.list, read_excel)
Run Code Online (Sandbox Code Playgroud)

此方法当然也可以与其他文件读取功能一起使用,如read.csvread.table.只需替换read_excel相应的文件读取功能,并确保使用正确的模式list.files.

如果您还想将文件包含在子目录中,请使用:

file.list <- list.files(pattern='*.xlsx', recursive = TRUE)
Run Code Online (Sandbox Code Playgroud)

用于读取Excel文件的其他可能包:openxlsxxlsx


假设列,对于每个文件一样,你可以集中在一个数据帧与约束他们bind_rows:

library(dplyr)
df <- bind_rows(df.list, .id = "id")
Run Code Online (Sandbox Code Playgroud)

或者rbindlist来自:

library(data.table)
df <- rbindlist(df.list, idcol = "id")
Run Code Online (Sandbox Code Playgroud)

两者都可以选择添加id用于标识单独数据集的列.


更新:如果您不想要数字标识符,只需使用sapplywith simplify = FALSE来读取以下文件file.list:

df.list <- sapply(file.list, read.csv, simplify=FALSE)
Run Code Online (Sandbox Code Playgroud)

当使用bind_rowsdplyrrbindlistdata.table,该id列现在包含文件名.

甚至另一种方法是使用purrr-package:

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")
Run Code Online (Sandbox Code Playgroud)

获取命名列表的其他方法:如果您不想只是一个数字标识符,那么在将它们绑定在一起之前,您可以将文件名分配给列表中的数据帧.做这件事有很多种方法:

# 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)
Run Code Online (Sandbox Code Playgroud)

现在,您可以dataframes列表放在一个数据帧与绑定rbindlistdata.tablebind_rowsdplyr.该id列现在将包含文件名而不是数字标识符.