glob2rx,在表达式中间放置一个通配符并指定exeptions,r

时间:2017-09-19 23:23:27

标签: r

我正在编写一个R脚本,它为一系列子目录中的所有文件执行一个函数。我遇到了一个问题,我的glob2rx函数正在识别这些子目录中的几个文件,我需要帮助改进我的模式,以便我可以选择我想要的文件。

以下是我的目录结构示例:

subdir1
   file1_aaa_111_subdir1.txt
   file1_bbb_111_subdir1.txt
   file1_aaa_subdir1.txt


subdir2
   file1_aaa_111_subdir2.txt
   file1_bbb_111_subdir2.txt
   file1_aaa_subdir2.txt

我想选择每个目录中的最后一个文件,尽管在我的实际目录中它的位置是多变的。我想使用类似的东西:

inFilePaths = list.files(path=".", pattern=glob2rx("*aaa*.txt"), full.names=TRUE)

但我没有得到任何文件。在查看此模式时,理论上我会在每个目录中获取第一个和最后一个文件。意思是我需要编写一个异常来排除aaa_111文件,并保留aaa_subdir文件。

我一直在考虑第二种选择,但缺乏实现的能力。请注意,子目录的名称位于每个文件名的末尾。是否可以提取目录名称,然后将其与glob2rx模式组合,然后直接指定我想要的文件?像这样:

#list all the subdirectories
subDirsPaths = list.dirs(path=".", full.names=TRUE)

#perform a function on these directories one by one    
  for (subDirsPath in subDirsPaths){
#make the subdirectory the working directory 
  setwd("/home/phil/Desktop/working")
  setwd(paste(subDirsPath, sep=""))

  # get the working directory name, and trim the "./" from it
  directory <- gsub("./", "", paste(subDirsPath, sep=""))

# attempt to the get the desired file by pasting the directory name into the glob2rx funtion 
  inFilePaths = list.files(path=".", pattern=glob2rx("*aaa_", print(directory,".txt")), full.names=TRUE)
  for (inFilePath in inFilePaths)
  {
    inFileData <- read_tsv(inFilePath, col_names=TRUE)
  }

}

1 个答案:

答案 0 :(得分:0)

通过一些修改,第二个选项运作良好。我最终使用粘贴与print结合如下:

inFilePaths = list.files(path=".", pattern=glob2rx(print(paste("*", "aaa_", directory, ".txt", sep=""))), full.names=TRUE)

粘贴功能将文本合并为一个字符串,该字符串还保留了通配符。 print函数将它添加到list.files函数作为glob2rx模式。

虽然这并不允许我在表达式的中间放置一张外卡,我相信这样做是使用转义字符,但它并没有解决在野外放置异常的需要卡,它适用于我的目的。

我希望这有助于我的职位。