4.5 C
London
Thursday, December 19, 2024
HomeRImport & Export Data in RHow to Rename Files in R (With Examples)

How to Rename Files in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories