[R] Formating numbers

Charilaos Skiadas cskiadas at gmail.com
Mon May 5 13:25:07 CEST 2008


On May 5, 2008, at 7:03 AM, pecardoso wrote:

> Maybe a very, very basic question but how can I get a vector of  
> values with the specific format:
> 001,002,010,100
>
> instead of:
> 1,2,10,100

Not perfect, but might get you started:

sprintf("%03d",c(8:10,101))

or

formatC(c(8:10,101), width=3, flag="0")

For a better solution, so as not to hard-code the width:

paddedZeros <- function(x) {
	formatC(x, width=max(nchar(x)), flag="0")
}
paddedZeros(c(8:10,101))

> Paulo

Haris Skiadas
Department of Mathematics and Computer Science
Hanover College



More information about the R-help mailing list