Padding integers for use in filenames

September 29, 2012

(This article was first published on bayesianbiologist » Rstats, and kindly contributed to R-bloggers)

If you’ve ever written code that generates a whole whack of files, you may have came across the following problem when processing them. Using a naming convention wherein files are numbered will  gum up any ordering which is based on string sorting (ls, for example). What you end up with is something like this:


Which is just no good, no good at all. A solution to this is to pad the file number with zeros, like so:


I wrote a little function to make this easy:

  out_string<-paste(10*scale + n,sep='')

*EDIT: Very soon after posting this, ggplot creator and general rstats rockstar Hadley Wickham noted on twitter that you can do this in one line using:

sprintf(“%03d”, 1)

Then, simply pass this function your file number (n) and the number of zeros that you’d like to pad it with (scale). This should be the order of magnitude of the number of files you’re creating. For example:

for(i in 1:1000){

This little bit of code came in quite handy in generating this video of dispersal on a discrete lattice. Enjoy!

To leave a comment for the author, please follow the link and comment on their blog: bayesianbiologist » Rstats. 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...

Tags: , , , ,

Comments are closed.


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)