[R] format integer numbers with leading 0

David Wolfskill r at catwhisker.org
Thu Jan 4 21:15:11 CET 2018


On Thu, Jan 04, 2018 at 09:12:12PM +0100, Marc Girondot via R-help wrote:
> Dear R-er,
> 
> I would like format integer number as characters with leading 0 for a 
> fixed width, for example:
> 
> 1 shoud be "01"
> 2 shoud be "02"
> 20 should be "20"
> 
> Now I use:
> 
> x <- c(1, 2, 20)
> 
> gsub(" ", "0", format(x, width=2))
> 
> But I suspect more elegant way could be done directly with format 
> options, but I don't find.

> x <- c(1, 2, 20)
> sprintf("%02d", x)
[1] "01" "02" "20"
> 

Peace,
david
-- 
David H. Wolfskill				r at catwhisker.org
If you want the best Fake News, go to the best source of it: Donald J. Trump.

See http://www.catwhisker.org/~david/publickey.gpg for my public key.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 603 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20180104/72ecb827/attachment.sig>


More information about the R-help mailing list