I need to copy files from multiple folders into one folder, but there are multiple duplicates and I need to keep those. Is there a way to copy files with duplicate filenames into one directory and retain both files by having the duplicate(s) rename automatically in R?

The code I'm using:

my_dirs <- list.dirs("C:/desktop/")
library(plyr)
files<-sapply(my_dirs,list.files,full.names=TRUE,pattern=".xlsx")

new_dir<-"C:/desktop/new folder/"

for(file in files) {
  file.copy(file, new_dir)
}
1

There are 1 answers

1
lmo On BEST ANSWER

You can probably use file.rename instead. I believe this code should work, but haven't tested it.

for(i in seq_along(files)) {
  file.rename(files[i], paste0(new_dir, "file_", i, basename(files[i])))
}

The second argument to file.rename pastes the new file path to the file name prepended with "file_", and a counter. basename strips the original file path and returns only the name of the file. With the addition of the counter, you can be sure that none of the files have the same name.