Format number as fixed width, with leading zeros

R

R Problem Overview


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.)

R Solutions


Solution 1 - R

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionahs85View Question on Stackoverflow
Solution 1 - RAndrieView Answer on Stackoverflow