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

Gregor GORJANC gregor.gorjanc at bfro.uni-lj.si
Wed Jan 5 16:17:48 CET 2005


Hello!

I am producing a set of images and I would like them to be sorted by names 
I give. I was able to produce my names and add integer to them. That is 
easy. But my problem lies in sort of file from this process:

figure_10.png
figure_11.png
figure_12.png
...
figure_1.png
figure_20.png
...

So I would like to convert integers to something like 01 if upper limit for
this conert is 10 or 001 for 100. I wrote a simple function (see below), 
but I do not know how this limit stuff can be imporved to work really well 
with default. Any suggestions?

int2char <- function(x, limit = max(x)) {

     # Description:
     # Converts integer to character such that numbers bellow limit get 0 in
     # front
     # Gregor GORJANC, 2005-01-05

     # Arguments:
     # x: vector of numbers
     # limit: limit up to which numbers should get 0 in front, default
     #        max(x)

     # Examples:
     # a <- seq(0, 20, 1)
     # int2char(a) # this does not work OK
     # int2char(a, limit = 10) # this does work OK

     # How to:
     # I would like that default would be more efficient - so it would
     # recognize that let say limit 20 in example above should actually be
     # 10 and so on.

     # Code:
     for (i in 1:length(x)) {
         if (x[i] < limit) {
             n[i] <- paste("0", x[i], sep  = "")
         } else {
             n[i] <- as.character(x[i])
         }
     }
     return(n)
}


-- 
Lep pozdrav / With regards,
     Gregor GORJANC

---------------------------------------------------------------
University of Ljubljana
Biotechnical Faculty       URI: http://www.bfro.uni-lj.si
Zootechnical Department    mail: gregor.gorjanc <at> bfro.uni-lj.si
Groblje 3                  tel: +386 (0)1 72 17 861
SI-1230 Domzale            fax: +386 (0)1 72 17 888
Slovenia




More information about the R-help mailing list