[R] add leading zeros

Liviu Andronic landronimirc at gmail.com
Wed Aug 8 07:55:33 CEST 2012


On Tue, Aug 7, 2012 at 10:48 PM, David Winsemius <dwinsemius at comcast.net> wrote:
> On Aug 7, 2012, at 3:55 AM, Liviu Andronic 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)
>> }
>
> Thanks, Liviu;
>
Glad this helped.


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



More information about the R-help mailing list