How to move files from one folder to another in R?

Viewed 2213

I know this question has been asked before, but there is a slight variation than just using the file.rename() function.

I created a variable that uses the setdiff function to compare what files Folder 1 has that Folder 2 does not. There are about ~100 files in Folder 1 that Folder 2 does not have, based on name of the file. I wanted to move these 100 files into Folder 3.

How would I go about doing that?

Would I use an if then statement?

1 Answers

Assuming you have a list of the names you want to copy and the destination folder already exists:

# vector with the 100 files names to be copied
names <- c("text1.txt", "text2.txt") 

# custom function
my_function <- function(x){
  file.rename( from = file.path("yourpath/folder1", x) ,
               to = file.path("yourpath/folder3", x) )
}

# apply the function to all files
lapply(names, my_function)

Note that rename actually deletes the files in the from folder. If you do not want that you can use file.copy

Related