[R] pad leading zeros in front of strings

R. Michael Weylandt michael.weylandt at gmail.com
Tue May 22 20:55:50 CEST 2012


Please do reply to the list -- I'm not on Windows so someone else will
have to pick the question up to help you out.

It's not great, but you could do something like

zeroPad <- function(str, len.out, num.zeros = len.out[1] - nchar(str)){
   paste0(paste(rep("0", num.zeros), collapse = ""), str)
}

as a temporary work-around. Probably possible to vectorize that pretty
easily as well.

Best,
Michael

On Tue, May 22, 2012 at 2:50 PM, Hui Du <Hui.Du at dataventures.com> wrote:
> Thank you for your replay. Yes, I am on windows.
>
> Best Regards,
> Hui Du
>
> Data Ventures Inc
>
> -----Original Message-----
> From: R. Michael Weylandt [mailto:michael.weylandt at gmail.com]
> Sent: Tuesday, May 22, 2012 11:49 AM
> To: Hui Du
> Cc: r-help at r-project.org
> Subject: Re: [R] pad leading zeros in front of strings
>
> I think once upon a time this was found to be OS-dependent since it
> calls the system's C  sprintf()  -- I get the leading zeros on Mac. I
> presume you're on Windows?
>
> Michael
>
> On Tue, May 22, 2012 at 2:41 PM, Hui Du <Hui.Du at dataventures.com> wrote:
>> Dear All,
>>
>> This question sounds very simple but I don't know where I am wrong. I just want to pad leading zeros in some string, for example, "123" becomes "00123". What is wrong if I do following?
>>
>>> sprintf("%05s", "123")
>> [1] "  123"
>>
>>
>> It didn't return "00123", instead it padded with 'blank'.
>>
>>
>> Thank you for your help in advance.
>>
>> HXD
>>
>>        [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list