nikopartanen
nikopartanen

Reputation: 617

list.files - exclude folder

I want to use R's list.files function to find all text files in a folder and in its subfolders. However, I would like to exclude all files that are in one subfolder, let's say it contains unfinished work which is not ready for the things I use the other files for. Structure is like this:

- folder
 |- subfolder_1_good_stuff
 |- subfolder_2_good_stuff
 |- subfolder_3_good_stuff
 |- subfolder_4_unfinished_stuff

So "folder" would be my working directory.

I would now use:

list.files(path=".", pattern=".txt", recursive=TRUE)

But what should I add to "path" expression in order to exclude folder with unfinished stuff. This folder name will not be present in any filenames, if that makes some difference.

Upvotes: 18

Views: 10997

Answers (2)

Emman
Emman

Reputation: 4201

Building upon @zx8754's answer, just with tidyverse approach using %>%:

library(tidyverse)

list.files(path=".", pattern=".txt", full.names = TRUE, recursive=TRUE) %>%
   stringr::str_subset(., "unfinished_stuff", negate = TRUE)

Upvotes: 8

zx8754
zx8754

Reputation: 56249

Use regex - grepl to exclude:

# find all ".txt" files
myfiles <- list.files(path = ".", pattern = ".txt",
                      full.names = TRUE, recursive = TRUE)

# exclude unfinished stuff
myfilesfinished <- myfiles[ !grepl("unfinished_stuff", myfiles) ]

Upvotes: 14

Related Questions