[R] add leading zeros

David Winsemius dwinsemius at comcast.net
Tue Aug 7 22:48:13 CEST 2012


On Aug 7, 2012, at 3:55 AM, Liviu Andronic wrote:

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

Thanks, Liviu;

Your post prompted me to add a variant in my .Rprofile that adds  
leading zeros to numeric-date values in ddmmyyyy format which lost  
them because they were imported as integers" (because I forgot to use  
colClasses.)

add.dt0 <- function(x, width=8 ){
     sprintf(paste('%0', width, switch(is.numeric(x)+1, 's', 'i'),  
sep=''), x)
  }

Can also be used for Excel (character) output that omits the leading 0  
in date fields that were output in csv-format as  m/dd/yy.

#character input
dts <- ("7/12/08",  "11/11/11")
  as.Date(add.dt0(dts), format="%d/%m/%y", origin="1970-01-01")
#[1] "2008-12-07" "2011-11-11"

# numeric input
  as.Date(add.dt0(1122011), format="%d%m%Y", origin="1970-01-01")
#[1] "2011-12-01"

 > as.Date(1122011, format="%d%m%Y", origin="1970-01-01")
[1] NA
 > as.Date(add.dt0(1122011), format="%d%m%Y", origin="1970-01-01")
[1] "2011-12-01"
 > as.Date(01122011, format="%d%m%Y", origin="1970-01-01")
[1] NA
 > as.Date(add.dt0(01122011), format="%d%m%Y", origin="1970-01-01")
[1] "2011-12-01"


-- 
David.
>
>> 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
>

David Winsemius, MD
Alameda, CA, USA



More information about the R-help mailing list