DJ-AFC DJ-AFC - 19 days ago 5
R Question

create sequence of numbers with leading zeroes

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.

Answer

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"