Home » How to Rename Files in R (With Examples)

How to Rename Files in R (With Examples)

by Erma Khan

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"

Notice that “good” has been replaced with “bad” in the name of every CSV file.

Related: How to Use str_replace in R

Additional Resources

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

How to Import CSV Files into R
How to Import Excel Files into R
How to Use setwd / getwd in R

Related Posts