format integer numbers with leading 0

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

format integer numbers with leading 0

R help mailing list-2
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.

Thanks a lot

Marc

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: format integer numbers with leading 0

David Wolfskill
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 [hidden email]
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.

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

signature.asc (616 bytes) Download Attachment
Reply | Threaded
Open this post in threaded view
|

Re: format integer numbers with leading 0

lasse.kliemann
In reply to this post by R help mailing list-2
Marc Girondot via R-help <[hidden email]> writes:

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

formatC(x, width=2, flag="0")

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

signature.asc (847 bytes) Download Attachment