How do I rename files using R?

sacvf picture sacvf · May 25, 2012 · Viewed 83.6k times · Source

I have over 700 files in one folder named as: files from number 1 to number9 are named for the first month:

water_200101_01.img  
water_200101_09.img  

files from number 10 to number30 are named:

water_200101_10.img
water_200101_30.img

And so on for the second month: files from number 1 to number9 are named:

water_200102_01.img  
water_200102_09.img  

files from number 10 to number30 are named:

water_200102_10.img
water_200102_30.img 

How can I rename them without making any changes to the files. just change the nams, for example

water_1
water_2
...till...
water_700

Answer

Brian Diggs picture Brian Diggs · May 25, 2012

file.rename will rename files, and it can take a vector of both from and to names.

So something like:

file.rename(list.files(pattern="water_*.img"), paste0("water_", 1:700))

might work.

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 (although I note that 700 is not a multiple of 30).

I will set aside the question, "why would you want to?" since you seem to be throwing away information in the filename, but presumably that information is contained elsewhere as well.