[R] adding zero to a number vector

Marc Schwartz marc_schwartz at me.com
Mon Nov 9 16:42:03 CET 2009


On Nov 9, 2009, at 9:34 AM, anna freni sterrantino wrote:

> Hi !
> I'd like to create
> a vector
> that has  this kind of numeration
> 001
> 002
> 003
> .
> .
> .
> 099
>
> I have looked at format help page but couldn't get
> any hint on how to do it.
> Thanks
>
> Anna


See ?sprintf

 > sprintf("%03d", 1:99)
  [1] "001" "002" "003" "004" "005" "006" "007" "008" "009" "010" "011"
[12] "012" "013" "014" "015" "016" "017" "018" "019" "020" "021" "022"
[23] "023" "024" "025" "026" "027" "028" "029" "030" "031" "032" "033"
[34] "034" "035" "036" "037" "038" "039" "040" "041" "042" "043" "044"
[45] "045" "046" "047" "048" "049" "050" "051" "052" "053" "054" "055"
[56] "056" "057" "058" "059" "060" "061" "062" "063" "064" "065" "066"
[67] "067" "068" "069" "070" "071" "072" "073" "074" "075" "076" "077"
[78] "078" "079" "080" "081" "082" "083" "084" "085" "086" "087" "088"
[89] "089" "090" "091" "092" "093" "094" "095" "096" "097" "098" "099"


Note the format specifies that the argument 1:99 should be formatted  
with leading zeroes to fill a 3 character width output.

Importantly, note that the result is a character vector and not  
numeric values, though you can coerce back to numeric with ?as.numeric.

HTH,

Marc Schwartz




More information about the R-help mailing list