1

Possible Duplicate:
Format number as fixed width, with leading zeros
sprintf use without gsub

This has probably been done before but I couldn't find a thread for R.

How would I increment leading zeroes in R?

For example have a vector called x with elements: 0001, 0002, 0003....9999

Community
  • 1
  • 1
user1103294
  • 423
  • 3
  • 6
  • 16
  • 1
    Looks like it has been asked before: http://stackoverflow.com/questions/5812493/adding-leading-zeros-using-r and http://stackoverflow.com/questions/12379767/sprintf-use-without-gsub . Both found with search: [r] leading zeros – IRTFM Oct 24 '12 at 04:52
  • 1
    Just found a third: http://stackoverflow.com/questions/8266915/format-number-as-fixed-width-with-leading-zeros .... yeah, I know... get a life. – IRTFM Oct 24 '12 at 04:58
  • whoops i should prolly delete this then. thanks! – user1103294 Oct 24 '12 at 04:59
  • I'm not sure you can anymore. We can close it, though. – IRTFM Oct 24 '12 at 05:03

2 Answers2

1

Use sprintf:

sprintf("%04s", as.character(1:20))
[1] "0001" "0002" "0003" "0004" "0005" "0006" "0007" "0008" "0009" "0010" "0011" "0012" "0013" "0014" "0015" "0016"
[17] "0017" "0018" "0019" "0020"

On Windows I am able to locate an Rhelp posting that says you can get success with

head( sprintf("%04d", 1:999)  )
[1] "0001" "0002" "0003" "0004" "0005" "0006"
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Whoops, I think I completely misinterpreted this question. – Blue Magister Oct 24 '12 at 04:38
  • It's a question I have answered before on Rhelp more than once. I have to look up my earlier answer every time. I keep thinking it should be "%0000s" – IRTFM Oct 24 '12 at 04:40
  • hi DWin, I tried your answer but it's not working for me `code`> nums = sprintf("%04s", as.character(1:9999)); head(nums) [1] " 1" " 2" " 3" " 4" " 5" " 6"`code` There are no leading zeros, just empty spaces – user1103294 Oct 24 '12 at 05:06
  • Ah, then you must be on a different OS (than me on a Mac). The sprintf function calls system facilities. I get the predicted results: tail( sprintf("%04s", as.character(1:999)) ) [1] "0994" "0995" "0996" "0997" "0998" "0999" – IRTFM Oct 24 '12 at 05:13
0

If the elements are all 4 digits, then regex could do it:

gsub("0(\\d{3})","1\\1",x)

More generally:

gsub("^0(\\d*)$","1\\1",x)
Blue Magister
  • 13,044
  • 5
  • 38
  • 56