[R] add leading zeros

Liviu Andronic landronimirc at gmail.com
Tue Aug 7 12:55:31 CEST 2012


Hello


On Fri, Jul 27, 2012 at 6:54 AM, R. Michael Weylandt
<michael.weylandt at gmail.com> wrote:
> Much easier than you think:
>
> x <- c(1L, 9000L)
>
> sprintf("%05i",x)
>
For anyone interested, I came up with a small wrapper for the above:
add.lead <- function(x, width=max(nchar(x))){
    sprintf(paste('%0', width, 'i', sep=''), x)
}

> x <- c(1L, 15L, 234L, 9000L)
> (xa <- add.lead(x))
[1] "0001" "0015" "0234" "9000"
> nchar(xa)
[1] 4 4 4 4
> (xb <- add.lead(x, 5))
[1] "00001" "00015" "00234" "09000"
> nchar(xb)
[1] 5 5 5 5
> (xc <- add.lead(x, 15))
[1] "000000000000001" "000000000000015" "000000000000234" "000000000009000"
> nchar(xc)
[1] 15 15 15 15


Regards
Liviu



More information about the R-help mailing list