alexanderjansma
alexanderjansma

Reputation: 65

(R) My for-loop to add text to string-value doesn't work

I am trying to append text to a file name in R, using a for-loop, but this is not working. The file names have the names of 001 up to 100, and I want to read the files into R.

As such, I have to append "00" to the files that have a name-number below 10 (e.g. files 001 up to 009), and a "0" to files within the 10-100 range (e.g. files 010 up to 099), since the input into the function is a number range, for example files 15:70. Otherwise the files cannot be read into R.

I have tried to make a for loop using if-statements combined with the paste function to append "00"'s to the file names, but the for-loop does not output a correct new list of elements:

e.g. when I input files 1:100 in the function, I want the for loop to construct a new variable that has the 'correct' file names 001 up to 100 (with the correct amount of "00"'s appended in the front, as these are the directory file names).

convert <- function(id) {   

    for (i in length(id)) {

        if (id[i] > 0 && id[i]<= 10) {
            id[i] <- paste("00", id[i], sep="");    
        }
    }
    print(id); ## prints "10" (?)
}

So when I want to convert the vector 1:10, or "1, 2, 3, 4, etc" to "001, 002, 003, 004, etc.", I want to be able to do that using this for loop. However, the output of this function is only "10". As such it seems that it only takes the last element of the input vector to the end of the function.

Can anyone explain what is going wrong? Thank you in advance.

Upvotes: 0

Views: 1438

Answers (2)

Fernando
Fernando

Reputation: 141

Try this:

vector <- 1:100
vector2 <- character(100)

max.length <- 3

for(i in vector){
  vector2[i] <- paste(c(rep('0', max.length - nchar(vector[i])), 
                        as.character(vector[i])),
                      collapse = "")
}

vector2

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

You can change the max.length argument if you want to pad more zeros ahead.

Edit: I think Markus answer is easier.

Upvotes: 0

markus
markus

Reputation: 26343

You can generate this sequence using sprintf

sprintf("%03d", 1:100)
#[1] "001" "002" "003" "004" "005" "006" "007" "008" "009" "010" "011" ... "098" "099" "100"

Upvotes: 2

Related Questions