How to Rename a File in R

You can change a file name programmatically in R using a built-in function. Changing a file name is one of the most used operations when dealing with many files. Let’s see how to rename files in R programmatically.

Rename a File in R

To rename a file in R, use the file.rename() function. The file.rename() method will rename files, and it can take a vector of both from and to names.


file.rename(from, to)


The from, to are character vectors containing file names or paths for file.copy and file.symlink and Sys.junction that can alternatively be the path to a single existing directory.


Before renaming a file, we need to check if the file exists or not. To check if the file exists in R, use the file.exists() method.

file <- "dataframe.R"

if (file.exists(file)) {

 file.rename("dataframe.R", "data.R")

} else {

 cat("The file does not exist")



[1] TRUE

It returns TRUE that means the file is successfully renamed to data.R.

If care about the order specifically, you could either sort the list of files that currently exist, or if they follow a particular pattern, just create the vector of filenames directly.

rename.files() in R

In previous R version, to rename a file recursively in R, use the rename.files() method.


rename.files(dir, pattern, replacement)


dir: It is a Path to the directory for which you want to change the file names.
pattern: It is a Pattern in the file name to replace.
replacement: It is the Text to replace a pattern with.
That is it for renaming a file in R.

See also

Removing a file in R

Leave a Comment