[R] pad leading zeros in front of strings

Sarah Goslee sarah.goslee at gmail.com
Tue May 22 20:57:27 CEST 2012


Michael, I'm curious: if you pass sprintf() a string, it still pads
with zeros? What's the output of:

sprintf("%05s", "123")
sprintf("%05s", "abc")

On linux, sprintf() pads strings with spaces, as you'd expect. Padding
strings with zeros is... odd.

Sarah

> sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: x86_64-redhat-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=C                 LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] tools_2.15.0

On Tue, May 22, 2012 at 2:49 PM, R. Michael Weylandt
<michael.weylandt at gmail.com> wrote:
> 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
>>

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list