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)
}
You can probably use
file.rename
instead. I believe this code should work, but haven't tested it.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.