Copying Files from a Directory in R

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.

Syntax

file.copy(from, to, overwrite = recursive, recursive = FALSE,
          copy.mode = TRUE, copy.date = FALSE)

Parameters

  1. 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.
  2. 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’.
  3. recursive: It is logical. If to is a directory, should directories from being copied (and their contents)?
  4. copy.mode: It is logical, should file permission bits be copied where possible?
  5. copy.date: It is logical, should file dates be preserved where possible?

Example

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)

Output

[1] TRUE
[1] 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.

See also

Move Files in R

Rename a File in R

Check if the File exists in R

How to Remove Files in R

Leave a Comment