递归搜索子目录以找到文件的第一个实例

Recursively search subdirectories to find the first instance of file

我有一个复杂的数据集,分布在每个城市 (C) 的 80 个目录中。这些城市中的每一个都有多个不同深度的不相同的子目录。澄清这意味着举个例子:城市 1 可以有 5 个子目录 a-e,其中每个子目录又可以有多个子目录。现在我需要在每个终端子目录中找到 .txt 文件的第一个实例,并将函数应用于 txt 文件(已经编写的逻辑函数)。终端前子目录中没有 .txt 文件。

 lapply(list.dirs,function(x) {
if length(list.files(path=x,pattern=".txt"))==0 { 
**apply function to .txt file}**
else {**lapply list.dirs etc---**} 

但是,我以这种方式留下了一个永无止境的循环。如何有效地完成这项工作?

您可能需要这样的东西:

Treat_txt<-function(direct){
                if(length(list.files(direct,pattern=".txt"))){
                     do what you need to do with the text file
                } else {
                     dirs<-list.dirs(direct,full.names=T,recursive=F)
                     sapply(dirs,Treat_txt)
                }
           }

然后就可以用"top"目录的路径调用函数了