Search code examples
r

Use wildcard in path for list.files


I need to use wildcard in my path, but somehow this is not recognised by R. The path is correct. Any idea why it fails?

 list.files(path = paste0("./Unzipped/",input_files[1],"/Variants/*/"), pattern = "tsv$")
 character(0)

File in located here:

"./Unzipped/FolderLoop/Variants/FolderNameVaries/file1.tsv"

Solution

  • List files with file pattern, and recursively:

    x <- list.files(path = "./Unzipped/", pattern = "*.tsv", recursive = TRUE)
    
    #it should return something like this:
    x <- c("./Unzipped/FolderLoop1/Variants/FolderNameVaries/file11.tsv",
           "./Unzipped/FolderLoop2/Variants/FolderNameVaries/file22.tsv",
           "./Unzipped/FolderLoop3/Variants/FolderNameVaries/file33.tsv")
    

    Then use regex to match folders:

    grep("FolderLoop1", x, value = TRUE, fixed = TRUE)
    # [1] "./Unzipped/FolderLoop1/Variants/FolderNameVaries/file11.tsv"