[R] pad leading zeros in front of strings

Rui Barradas ruipbarradas at sapo.pt
Tue May 22 23:20:53 CEST 2012


Hello,

I believe there's nothing OS dependent about this:

# pad with zeros
padz <- function(x, n=max(nchar(x))) gsub(" ", "0", formatC(x, width=n))

padz(c(1, 10, 100), 5)
padz(c("a", "aa"))
padz(c("a", "aa"), 5)

Rui Barradas

Michael Weylandt 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@> 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@ 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.
> 
> ______________________________________________
> R-help@ 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.
> 


--
View this message in context: http://r.789695.n4.nabble.com/pad-leading-zeros-in-front-of-strings-tp4630964p4630995.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list