R导入一些以相同字符串开头的xlsx文件,忽略同一文件夹中的其他文件

R import some xlsx files starting with same string, ignore the other in the same folder

我想将一些 xlsx 文件导入 rstudio。 这些文件都在同一个文件夹中,但是里面还有一些我不感兴趣的其他 xlsx 文件:

我想导入所有四个“Alles_....”文件,构建一个包含所有这些数据的数据框(例如称为 All)。我希望该函数忽略所有其他不以“Alles_”开头的文件

我可以使用哪个功能?

提前致谢!

list.files 将创建一个文件名向量,模式参数就像一个过滤器,它只会匹配其中包含 Alles 的文件。 map_dfr 是一种执行 for 循环并将表绑定在一起的奇特方法。如果所有 alles 文件表的结构都不相同,您可能需要先尝试 map 本身。这将 return 一个列表,以便您可以检查它们。 read_xlsx会如你所想。你可能需要弄清楚你需要的文件中的sheet是什么,默认是工作簿中的第一个sheet。

library(purrr)
library(magrittr)
library(readxl)
list.files(path = "directory they live", 
           pattern = "Alles_", 
           full.names = TRUE) %>% 
  map_dfr(., read_xlsx)

首先,我会用 setwd() 设置工作目录,然后:

dir()[grepl('Alles', ignore.case = T, dir())] -> files    
do.call('rbind', lapply(files, function(file) openxlsx::read.xlsx(file)))

如果你想要第二个sheet:

do.call('rbind', lapply(files, function(file) openxlsx::read.xlsx(file, sheet = 2)))