[R] adding zero to a number vector

Don MacQueen macq at llnl.gov
Mon Nov 9 18:08:26 CET 2009


Also,

   formatC(3,width=3,flag='0')

formatC and sprintf are both referenced in the "See Also" part of the 
format help page.

-Don

At 9:42 AM -0600 11/9/09, Marc Schwartz wrote:
>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
>
>______________________________________________
>R-help at r-project.org 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.


-- 
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062




More information about the R-help mailing list