I have a list of many directories, each of which have 5 files inside, from these files within each directory I want to select one (for example let us say the one with extension .txt) and compile a list of these .txt files....how do I create a loop that selects txt files from a list of directories in R?
问题:
回答1:
You can do:
dir(path = ".", pattern = "\\.txt$", full.names = TRUE, recursive = TRUE)
Where path
is the root that contains all the folders you want to look up, pattern
is regular expression that matches the files you are interested in (in the example all the files with the .txt
extension, full.names
return the full path of the files, and recursive
to explore all the subfoders in path
. This returns a vector with the full path for the files that match your query.
回答2:
If you have the list of directory names in dirs
,
you can get the .txt
files in all of them as a vector with:
files <- unlist(lapply(dirs, function(dir) list.files(path = dir, pattern = '\\.txt$')))
You can achieve the same using a loop as you asked, but it's less elegant, and I don't recommend it:
files <- c()
for (dir in dirs) {
files <- c(files, list.files(path = dir, pattern = '\\.txt$'))
}
回答3:
list.files
is a vectorized function already, so you can pass the vector of directories to it, no loop needed.
my_dirs <- c("foo/bar", "foo/baz")
all_text_files <- list.files(my_dirs, pattern = "\\.txt$", full.names = TRUE)
If you want a list separating files by directory...
split(all_text_files, dirname(all_text_files))