How do I rename files using R?

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.

Leave a Comment