Programatically rename files (or do other stuff to them) in R

February 29, 2012

(This article was first published on W. Andrew Barr's Paleoecology Blog, and kindly contributed to R-bloggers)

In order to do something to a bunch of files at once, we first need a vector which contains the file paths of just the files we are interested in.



[1] “/myDirectory/xxxFile1.txt”
[2] “/myDirectory/xxxFile2.txt”
[3] “/myDirectory/xxxFile3.txt”
[4] “/myDirectory/xxxFile4.txt”
[5] “/myDirectory/xxxFile5.txt”
[6] “/myDirectory/xxxFile6.txt”

Once you have a vector that consists of a bunch of file paths, you can do useful stuff with it, like renaming files in a consistent way. I can use sapply() to apply a function to every element of a vector.  For example, I can use the file.rename() function along with the sub() function to change the filename.



If you aren’t familiar with sapply(), I highly recommend you take a moment to study up on how it works.  Using the apply() family of functions is really important to being productive in R.  Now my filenames look like this.

[1] “/myDirectory/NewTextStringFile1.txt”
[2] “/myDirectory/NewTextStringFile2.txt”
[3] “/myDirectory/NewTextStringFile3.txt”
[4] “/myDirectory/NewTextStringFile4.txt”
[5] “/myDirectory/NewTextStringFile5.txt”
[6] “/myDirectory/NewTextStringFile6.txt”

This is a whole lot faster and less error prone than trying to rename 500 files by hand.  Just type ?files for a list of other file functions that might be useful, like file.move() and unlink().  Be careful with unlink()….it will delete files from your machine!

To leave a comment for the author, please follow the link and comment on their blog: W. Andrew Barr's Paleoecology Blog. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)