Togaware DATA MINING
Desktop Survival Guide
by Graham Williams
Google

Automatically Generate Filenames

To generate a series of filenames, all with the same base name but having a sequence of numbers, as might be the case when you generate a sequence of plots and want to save each to a different file, the traditional R approach is to use formatC:

paste("df", formatC(1:10, digits=0, wid=3, format=d, flag="0"), ".dat", sep="")
 [1] "df001.dat" "df002.dat" "df003.dat" "df004.dat" "df005.dat" "df006.dat"
 [7] "df007.dat" "df008.dat" "df009.dat" "df010.dat"

Even easier though is to use the newer sprintf. Here's a couple of alternatives. The first assumes a fixed number of digits for the increasing number, whilst the second uses only the number of digits actually required, by finding out the number of digits using nchar:

> n <- 10
> sprintf("df%03d.dat", 1:10)
 [1] "df001.dat" "df002.dat" "df003.dat" "df004.dat" "df005.dat" "df006.dat"
 [7] "df007.dat" "df008.dat" "df009.dat" "df010.dat"
> sprintf("plot%0*d", nchar(n), 1:n)
 [1] "plot01" "plot02" "plot03" "plot04" "plot05" "plot06" "plot07" "plot08"
 [9] "plot09" "plot10"
> n <- 100
> sprintf("plot%0*d", nchar(n), 1:n)
  [1] "plot001" "plot002" "plot003" "plot004" "plot005" "plot006" "plot007"
 [...]
 [99] "plot099" "plot100"



Copyright © Togaware Pty Ltd
Support further development through the purchase of the PDF version of the book.
The PDF version is a formatted comprehensive draft book (with over 800 pages).
Brought to you by Togaware. This page generated: Sunday, 22 August 2010