4

I need to convert a vector of single digit numbers (e.g. c(1, 2, 3, 45)) to a character vector where the length of each item is two, and it is stuffed with a zero before the actual number (e.g. c("01", "02", "03", "45").

I could swear that I've done this before in R with some clever function but I can't for the life of me find it or remember what it is... I don't think it's format(), but I might be amazed.

TL;DR:

What function do I need to convert this:

c(1, 2, 3, 45)

To this:

c("01", "02", "03", "45")

?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
brews
  • 661
  • 9
  • 23

2 Answers2

11

sprintf with a padding character:

sprintf("%02d",c(1,2,3,45))

You could also use formatC, it uses basically the same set of formatting conventions (from the C standard library):

formatC(c(1,2,3,45),flag=0,width=2)

Also, a near-duplicate (sorry, didn't see it before I answered):

Format number as fixed width, with leading zeros

Community
  • 1
  • 1
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
2

How about a regex

sub('(^[0-9]$)','0\\1',c(1,2,3,45))
Jesse Anderson
  • 4,507
  • 26
  • 36