How to Rename Files in R?

Rename files in R using the file.rename() function. This function takes two parameters, the name of the file you want to rename and the new name you want for the file. It then uses the file path to locate and change the name of the file. This is a useful function when you want to keep files organized and want to easily find files by their new names.


You can use the following methods to rename files in R:

Method 1: Rename One File

file.rename(from='old_name.csv', to='new_name.csv')

Method 2: Replace Pattern in Multiple Files

file.rename(list.files(pattern ='old'),
            str_replace(list.files(pattern='old'), pattern='old', 'new'))

The following examples show how to use each method in practice.

Example: Rename One File

Suppose we have a folder with four CSV files in R:

#display all files in current working directory
list.files()

"data1.csv"  "data2_good.csv"  "data3_good.csv"  "data4_good.csv"

We can use the following code to rename the file called data1.csv to data1_good.csv:

#rename one file
file.rename(from='data1.csv', to='data1_good.csv')

#display all files in current working directory
list.files()

"data1_good.csv"  "data2_good.csv"  "data3_good.csv"  "data4_good.csv"

Notice that the file has been successfully renamed.

Example: Replace Pattern in Multiple Files

Suppose we have a folder with four CSV files in R:

#display all files in current working directory
list.files()

"data1_good.csv"  "data2_good.csv"  "data3_good.csv"  "data4_good.csv"

We can use the following code to replace “good” with “bad” in the name of every single file:

library(stringr)

file.rename(list.files(pattern ='good'),
            str_replace(list.files(pattern='good'), pattern='good', 'bad'))

#display all files in current working directory
list.files()

"data1_bad.csv"  "data2_bad.csv"  "data3_bad.csv"  "data4_bad.csv"

Related: 

The following tutorials explain how to perform other common operations with files in R:

x