Assuming I have 3 folders with a large number of files in each, I want to select only a few files from each sub-directory and paste only those files into a new folder. Let\'s ca
parent.folder <- "C:/Desktop/dir"
files <- list.files(path = parent.folder, full.names = T, recursive = T, include.dirs = T)
After this you need to select the relevant files:
files <- files[grep("wang\\.tax\\.sum", files)]
(Notice double-escapes before dots: \\.
- dot has a special meaning for grep.)
Or you could do this with pattern
argument to list.files in one step:
files <- list.files(path = parent.folder, full.names = T, recursive = T, include.dirs = T, pattern = "wang\\.tax\\.sum")
Creating new dir:
dir.create("taxsum", recursive = T)
Now you need to create new filenames:
newnames <- paste0("taxsum/", gsub("/|:", "_", files))
# replace "special" characters with underscore
# so that your file names will be different and contain the
# original path
# alternatively, if you know that file names will be different:
newnames <- paste0("taxsum/", basename(files))
And now you can use mapply
to copy (the same can be done with for
with a little extra effort):
mapply(file.copy, from=files, to=newnames)