Format number as fixed width, with leading zeros

ahs85 picture ahs85 · Nov 25, 2011 · Viewed 96.8k times · Source

The following code

a <- seq(1,101,25)
b <- paste("name", 1:length(a), sep = "_")

produces this output:

"name_1"  "name_26"  "name_51"  "name_76"  "name_101"

I'd like to have the same width of all values which means for me to fill the values with zeros like this:

"name_001"  "name_026"  "name_051"  "name_076"  "name_101"

How do I handle that?

(This question is related to this one.)

Answer

Andrie picture Andrie · Nov 25, 2011

There are several solutions to this.

One of them is to use sprintf. This uses C style formatting codes embedded in a character string to indicate the format of any other arguments passed to it. For example, the formatting code %3d means format a number as integer of width 3:

a <- seq(1,101,25)
sprintf("name_%03d", a)
[1] "name_001" "name_026" "name_051" "name_076" "name_101"

Another is formatC and paste:

paste("name", formatC(a, width=3, flag="0"), sep="_")
[1] "name_001" "name_026" "name_051" "name_076" "name_101"