Copying List of Files from One Folder to Other in R

Copying list of files from one folder to other in R

As Joran and Chase have already pointed out in the comments, all you need to do is:

file.copy(from=filestocopy, to=targetdir, 
overwrite = recursive, recursive = FALSE,
copy.mode = TRUE)

Then, if you're actually moving the files, remove the originals with:

file.remove(filestocopy)

Copy files from folders and sub-folders to another folder and saving the structure of the folders

You need to use the flag recursive = T inside the copy call, so you don't really need to loop inside the dir.

from = paste0(getwd(),"/output/","output_1")
to = paste0(getwd(),"/output/","output_1_copy")
file.copy(from, to, recursive = T)

Note that you need to create the /output_1_copy directory previously to the call. Yo can do it manually or using dir.create(...).

Copying specific files from multiple sub-directories into a single folder in R

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)

How can I copy files from folders and subfolders to another folder in R?

I would do:

from.dir <- "/Users/RLearner/Desktop/RDMS"
to.dir <- "/Users/RLearner/Desktop/Test"
files <- list.files(path = from.dir, full.names = TRUE, recursive = TRUE)
for (f in files) file.copy(from = f, to = to.dir)


Related Topics



Leave a reply



Submit