How to Copy a File in R

R provides many built-in functions that we can use to perform the file operations. Copy a file from one folder to another programmatically is one of the most important operations, and R provides a built-in function for that. Let’s see how to copy a file from one folder to another.

How to Copy a File in R

To copy a file in R, use the file.copy() method. The file.copy() function works in the same way as a file.append() function but with the arguments in the natural order for copying.

Copying to existing destination files is skipped unless overwrite = TRUE. The to argument can specify a single existing directory. If copy.mode = TRUE file read/write/execute permissions are copied where possible, restricted by ‘umask’.

Syntax

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

Arguments

from, to: They are character vectors containing file names or paths. For 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?

recursive: It is logical. If to is a directory, should directories in 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?

Copy a file in R Step by Step

In this example, we will copy a file from one current working directory to a new folder.

Step 1: Create a new directory

To get a current working directory using a command, use the getwd() function.

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 are creating a file using the file.create() function, and then define the new file’s path because we will 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. The complete code is below.

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 successfully creating a file and the second TRUE is for successfully copying the file.

If it returns FALSE, that means there is s some problem while copying the files.

That is it for copying a file in the R tutorial.

See also

How to Move Files in R

Get Extension of File in R

Rename a File in R

Check if the File exists in R

How to Remove Files in R

Leave a Comment