[R] Converting integers to chars i.e 1 to "01"

Martin Maechler maechler at stat.math.ethz.ch
Wed Jan 5 11:15:58 CET 2005


>>>>> "Eric" == Eric Lecoutre <lecoutre at stat.ucl.ac.be>
>>>>>     on Wed, 05 Jan 2005 10:29:48 +0100 writes:

    Eric> Hi Gregor,

    Eric> There still exist simple functions to achive that goal:

    Eric> Look at:
    >> x=1:111
    >> formatC(format="d",x,flag="0",width=ceiling(log10(max(x))))

    Eric> [1] "001" "002" "003" "004" "005" "006" "007" "008" "009" "010" "011" 
    Eric> "012" "013" "014" "015" "016" "017" "018" "019" "020"
    Eric> [21] "021" "022" "023" "024" "025" "026" "027" "028" "029" "030" "031" 
    Eric> "032" "033" "034" "035" "036" "037" "038" "039" "040"
    Eric> [41] "041" "042" "043" "044" "045" "046" "047" "048" "049" "050" "051" 
    Eric> "052" "053" "054" "055" "056" "057" "058" "059" "060"
    Eric> [61] "061" "062" "063" "064" "065" "066" "067" "068" "069" "070" "071" 
    Eric> "072" "073" "074" "075" "076" "077" "078" "079" "080"
    Eric> [81] "081" "082" "083" "084" "085" "086" "087" "088" "089" "090" "091" 
    Eric> "092" "093" "094" "095" "096" "097" "098" "099" "100"
    Eric> [101] "101" "102" "103" "104" "105" "106" "107" "108" "109" "110" "111"
    Eric> ? formatC

Yes; note also  "sprintf".

The folllowing shows it can even be simplified:

> (nn <- c(1:12, sort(outer(10^(2:4), -1:1, "+"))))
 [1]     1     2     3     4     5     6     7     8     9    10    11    12
[13]    99   100   101   999  1000  1001  9999 10000 10001

> formatC(nn, width=3, flag="0")
 [1] "001"   "002"   "003"   "004"   "005"   "006"   "007"   "008"   "009"  
[10] "010"   "011"   "012"   "099"   "100"   "101"   "999"   "1000"  "1001" 
[19] "9999"  "1e+04" "1e+04"
> formatC(nn, width=3, flag="0", format="fg")
 [1] "001"   "002"   "003"   "004"   "005"   "006"   "007"   "008"   "009"  
[10] "010"   "011"   "012"   "099"   "100"   "101"   "999"   "1000"  "1001" 
[19] "9999"  "10000" "10001"

> sapply(as.integer(nn), function(n) sprintf("%03d", n))
 [1] "001"   "002"   "003"   "004"   "005"   "006"   "007"   "008"   "009"  
[10] "010"   "011"   "012"   "099"   "100"   "101"   "999"   "1000"  "1001" 
[19] "9999"  "10000" "10001"


Martin




More information about the R-help mailing list