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")
?
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
How about a regex
sub('(^[0-9]$)','0\\1',c(1,2,3,45))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With