Copy Files from Directory & Folder in R (Example) | file.copy() Function
This article explains how to copy files between directories using the file.copy function in R programming.
Table of contents:
Let’s start right away:
Example Data
Consider the following working directories on the desktop of my computer:
As you can see in Figure 1, there are three files stored in a folder called “my directory A”, and there is a second directory called “my directory B” that is empty.
In the following example, I’ll explain how to create a copy in the second folder of the files in the first folder.
Let’s do this!
Example: Copy Files to Different Working Directory Using file.copy() Function
In this example, I’ll illustrate how to copy the files within a directory to another directory.
First, we have to create a list of all files in the first directory using the list.files function:
my_files <- list.files("C:/Users/Joach/Desktop/my directory A") # Get list of file names my_files # [1] "file no 1.docx" "file no 2.txt" "file no 3.xlsx"
As you can see based on the previous output of the RStudio console, the names of our example files have been stored in a character vector called my_files.
Next, we can apply the file.copy function to copy the files in the first folder to the second folder:
file.copy(from = paste0("C:/Users/Joach/Desktop/my directory A/", my_files), # Copy files to = paste0("C:/Users/Joach/Desktop/my directory B/", my_files)) # [1] TRUE TRUE TRUE
After executing the previous R code, our two folders look like this:
As you can see, all files are contained in both folders. Looks good!
Note that the file.copy function provides additional arguments (i.e. overwrite, recursive, copy.mode, copy.date) that I have not explained in this tutorial. Have a look at the help documentation of the file.copy command by executing ?file.copy in the RStudio console for more info.
Video, Further Resources & Summary
In case you need further explanations on the R programming code of this post, I can recommend watching the following video on my YouTube channel. In the video, I explain the R code of this article in the R programming language.
The YouTube video will be added soon.
In addition to the video, you might read the related tutorials on Statistics Globe.
- Move Files Between Folders in R
- How to Delete a File Using R
- Remove Extension from File Name in R
- system.file Function in R
- file.choose() & choose.files() Functions
- List of R Functions (Example Codes)
- Introduction to System Calls & Commands
- R Programming Examples
In this R programming tutorial you have learned how to copy files between folders on a computer using the file.copy function. Please let me know in the comments, in case you have further comments and/or questions.
Statistics Globe Newsletter