5

This question has been addressed previously using the Console.writelines function, but this is not available in my version of R and I can't find what package this belongs to.

I am simply trying to create a sequence of numbers from 0-99 with leading zeroes in the format "xxx", so my numbers should be 000, 001, 002... 099.

When I use:

seq(000:099)

R returns 1, 2, 3 etc.

Is there a simple way to do this? It strikes me that it should be far easier than it is.

This is different from previous answers as I need two zeroes in front of numbers 0-9 and just 1 zero in front of numbers 10-99 whereas the previous question just asked for 1 zero in front of all numbers.

DJ-AFC
  • 569
  • 6
  • 16
  • 2
    Use `sprintf`: like this `sprintf("%03.0f", 0:10)`. – lmo Nov 17 '16 at 15:03
  • Many thanks - this works really well and seems far simpler and more efficient than suggestions others have posted elsewhere – DJ-AFC Nov 17 '16 at 15:11
  • I think I better remove it alright, even though it isn't really a duplicate. I couldn't make the previous answers apply to my case – DJ-AFC Nov 17 '16 at 15:16
  • richie cotton and goodside's answer to the linked post are worth reading regarding the use of `sprintf`. – lmo Nov 17 '16 at 15:17

1 Answers1

13

For example 1:100 with leading zeroes up to three digits total:

sprintf('%0.3d', 1:100)
  [1] "001" "002" "003" "004" "005" "006" "007" "008" "009" "010" "011" "012"
 [13] "013" "014" "015" "016" "017" "018" "019" "020" "021" "022" "023" "024"
 [25] "025" "026" "027" "028" "029" "030" "031" "032" "033" "034" "035" "036"
 [37] "037" "038" "039" "040" "041" "042" "043" "044" "045" "046" "047" "048"
 [49] "049" "050" "051" "052" "053" "054" "055" "056" "057" "058" "059" "060"
 [61] "061" "062" "063" "064" "065" "066" "067" "068" "069" "070" "071" "072"
 [73] "073" "074" "075" "076" "077" "078" "079" "080" "081" "082" "083" "084"
 [85] "085" "086" "087" "088" "089" "090" "091" "092" "093" "094" "095" "096"
 [97] "097" "098" "099" "100"
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • Thanks for the useful solution guys, rather than joining those wrongly suggesting it is a duplicate. – DJ-AFC Nov 17 '16 at 15:14
  • I actually closed this as a duplicate. The answers in that question include the use case you need. See the `sprintf` part of Richies answer in the linked question. The answer of goodside in the same question even more clearly uses the exact same code I suggest here. – Paul Hiemstra Nov 17 '16 at 15:28
  • Okay, thanks Paul. Apologies for the duplication. – DJ-AFC Nov 17 '16 at 21:02