To copy a file from a directory in R, you can use the “file.copy()” method. For example, file.copy(“source.R”, “destination.R”) function creates a copy of the source.R as the destination.R in the same directory.
file.copy(from, to, overwrite = recursive, recursive = FALSE, copy.mode = TRUE, copy.date = FALSE)
- from, to: They are character vectors containing file names or paths. The file.copy() and file.symlink() can alternatively be the path to a single existing directory.
- overwrite: It is logical; should existing destination files be overwritten? If copy.mode = TRUE, file read/write/execute permissions is copied where possible, restricted by ‘umask’.
- recursive: It is logical. If to is a directory, should directories from being copied (and their contents)?
- copy.mode: It is logical, should file permission bits be copied where possible?
- copy.date: It is logical, should file dates be preserved where possible?
The file.copy() function works in the same way as a file.append() function but with the arguments in the natural order for copying. In this example, we will copy a file from one working directory to a new folder.
Step 1: Create a new directory
To create a directory in R, use the “dir.create()” method.
dir.create("newdir") newDirPath <- "newdir"
Here, we have also defined a new path in which we want to copy a file.
Step 2: Create a new file
To create a file in R, use the “file.create()” method.
files <- c("a.txt") file.create(files) newFilePath <- "a.txt"
Here, we have defined a vector containing a file name. Then we create a file using the file.create() function, then define the new file’s path because we need this in the copy() function.
Step 3: Copy a file from one folder to another.
To copy a file from one folder to another, use the “file.copy()” method.
dir.create("newdir") newDirPath <- "newdir" files <- c("a.txt") file.create(files) newFilePath <- "a.txt" file.copy(newFilePath, newDirPath)
 TRUE  TRUE
The first TRUE is for creating a file, and the second TRUE is for successfully copying the file.
If it returns FALSE, there are some problems copying the files.
Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.