How to Rename Files in R

How to Rename Files in R?, The methods listed below can be used to rename files in R:

How to Rename Files in R

The examples that follow demonstrate each technique in action.

Rename one file, for instance

Let’s say we have four CSV files in a folder in R:

list every file in the active working directory

list.files()
"data1.csv"  "data2_1.csv"  "data3_1.csv"  "data4_1.csv"

The data1.csv file can be renamed to data1new.csv using the code below.

Is It Difficult to Learn Data Science » finnstats

Rename one file

file.rename(from='data1.csv', to='data1new.csv')

Now we can display all files in the current working directory

list.files()
"data1new.csv"  "data2_1.csv"  "data3_1.csv"  "data4_1.csv"

Notice that the file has been successfully renamed.

Example: Replace Pattern in Multiple Files

Let’s say we have four CSV files in a folder in R:

List every file in the active working directory

list.files()
"data1_old.csv"  "data2_old.csv"  "data3_old.csv"  "data4_old.csv"

To change every file’s name from “old” to “new,” we can use the code below:

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

Now we can display all files in the current working directory

Data Science applications in Retail » finnstats

list.files()
"data1_new.csv"  "data2_new.csv"  "data3_new.csv"  "data4_new.csv"

Every CSV file’s name has been changed to read “new” instead of “old.”

How To Become A Quantitative Analyst » finnstats

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

four × one =