Explanation for sprintf("%03d", 7) functionality?

user3592253 picture user3592253 · May 18, 2014 · Viewed 25.3k times · Source

I am trying to write functions in R where the aim is to read multiple .csv files. They are named as 001.csv, 002.csv, ... 332.csv.

With paste I managed to construct names 1.csv, 2.csv and so on, but I'm having difficulty with adding leading zeroes. There's a hint that the construction like sprintf("%03d", 7) is required, but I have no idea why and how this works.

So can somebody explain what the following statement can actually does?

Answer

tonytonov picture tonytonov · May 18, 2014

sprintf originally comes from C and all formatting rules are taken from it as well. See ?sprintf in R or this or this reference to learn the subject in detail. Here I'll briefly outline what's the magic behind it.

"%03d" is a formatting string, which specifies how 7 will be printed.

  • d stands for decimal integer (not double!), so it says there will be no floating point or anything like that, just a regular integer.
  • 3 shows how many digits will the printed number have. More precisely, the number will take at least 3 digits: 7 will be __7 (with spaces instead of underscores), but 1000 will remain 1000, as there is no way to write this number with just 3 digits.
  • 0 before 3 shows that leading spaces should be replaced by zeroes. Try experimenting with sprintf("%+3d", 7), sprintf("%-3d", 7) to see other possible modifiers (they are called flags).

That being said, the output from sprintf("%03d", 7) will be 007.