处理每个包含R中多个文件的多个目录

我正在使用处理特定目录中的每个文件

files=list.files(path_of_directory, recursive=T, pattern='.xlsx') for(i in 1:length(files)) { #Some processing takes places which takes all files in a particular directory and produces single file } 

用于最终输出(在处理目录中的所有文件之后)的代码:

 write.xlsx(datasetr_df, file = file.path("Out_Put_Dir_Path", paste0("Manually_writting_name_output_name_same_as_Input_Dir",".xlsx")),sheetName="Sheet1",col.names=TRUE, row.names=FALSE) 

每次我改变目录的path来处理它包含的文件,而且我也习惯根据处理的目录来改变单个输出文件的名字。 假设目录是D1,D2和D3,每个都包含文件F1和F2。 有什么办法可以进一步自动化这个过程。 该程序执行以下步骤:1. Ist移动到特定的目录2.处理该目录中的所有文件,并且最终的sinle文件被赋予与目录相同的名称。 3.移动到下一个目录4.处理下一个目录中的所有文件,最后的单个文件被命名为与目录相同的名称。 5.这个过程继续,直到所有目录和包含的文件被处理。 所以如果有五个目录,则生成5个excel文件。 现在假设D1目录是进程,我应该得到输出作为D1处理。 如果能够帮助编写相同的代码,这将是非常有帮助的。

您可以将您的循环嵌套在两个级别中,以使第一级循环通过目录和第二级,但是通过每个目录中的文件循环。 考虑一下:

 #List all dirs you need to process dlist <- list.dirs("parent_dir") #parent dir==main dir with all the dirs #Loop over dirs for(d in dir_list){ #List files in d'th dir that need to be processed flist <- list.files(d, pattern='.xlsx') #Loop over files for(f in flist){ #Some processing takes places here } #Write output write.xlsx(datasetr_df, file=paste0(d,".xlsx"), sheetName="Sheet1",col.names=T, row.names=F) #Report progress print(paste0("Finished processing directory ", d)) } 

你可以继续使用相同的逻辑。 例如,将您的处理封装到您为每个目录调用它的函数中。

 lapply(list("path_d1","path_d2"), ## add list of directory here function(path_of_directory){ files=list.files(path_of_directory, recursive=TRUE, pattern='.xlsx') lapply(files ,function(file){ ## better to use lapply here than for loop ## Some processing takes places ## which takes all files in a particular directory ## and produces single file }) }) 

像这样做

 lapply(list.dirs("path",recursive = F),function(dir) {lapply(list.files(dir),function(file){read.csv(file)})}) 

这在链中使用了lapply

首先find所有的目录,然后对每个目录应用一个函数。 此内部函数列出该目录中的所有文件并应用读取csv文件的函数。

这是我读取文件的自定义function。 对于你的实现,只需用你写的函数replace内部函数来说明myfunction可以像这样处理单个文件并使用这个语句。

 lapply(list.dirs("path",recursive = F),function(dir) {lapply(list.files(dir),myfunction)})