0 votes
1 view
in R Programming by (5.3k points)

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?

1 Answer

0 votes
by (25.3k points)

To format numbers as fixed width with leading zeros added, you can use the sprintf() function from the base package.

Basic syntax for sprintf() is:

sprintf(fmt, ...)

Where,

fmt

a character vector of format strings, each of up to 8192 bytes.

...

values to be passed into fmt. Only logical, integer, real and character vectors are supported, but some coercion will be done: see the ‘Details’ section. Up to 100.

In your case:

a <- seq(1,101,25)

b <- paste("name",a, sep = "_")

sprintf("name_%03d", a)

[1] "name_001" "name_026" "name_051" "name_076" "name_101"

You can also use the paste function along with formatC as follows:

paste("name", formatC(a, width=3, flag="0"), sep="_")

[1] "name_001" "name_026" "name_051" "name_076" "name_101"

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...