Skip to content

add leading zeros

3 messages · David Winsemius, Liviu Andronic

#
Hello


On Fri, Jul 27, 2012 at 6:54 AM, R. Michael Weylandt
<michael.weylandt at gmail.com> wrote:
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)
}
[1] "0001" "0015" "0234" "9000"
[1] 4 4 4 4
[1] "00001" "00015" "00234" "09000"
[1] 5 5 5 5
[1] "000000000000001" "000000000000015" "000000000000234" "000000000009000"
[1] 15 15 15 15


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

            
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"
#
On Tue, Aug 7, 2012 at 10:48 PM, David Winsemius <dwinsemius at comcast.net> wrote:
Glad this helped.
In my case I had Excel mangle up Cusips:Losing leading zeros when
there was no letter as part of the Cusip (solved with my function
above), and interpreting Cusips containing an E (e.g. 12345E123) as
_very_ large numbers. This last part I had to correct manually.

Regards
Liviu