Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stuffing numbers when converting to characters [duplicate]

Tags:

format

parsing

r

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

?

like image 687
brews Avatar asked Dec 16 '22 01:12

brews


2 Answers

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

like image 124
Ben Bolker Avatar answered Dec 27 '22 10:12

Ben Bolker


How about a regex

sub('(^[0-9]$)','0\\1',c(1,2,3,45))
like image 45
Jesse Anderson Avatar answered Dec 27 '22 10:12

Jesse Anderson