Search code examples
rfor-loopconcatenation

For loop concatenates only last iteration. Why?


I want a vector with the excel-letters: c(A, B, C, ... Z, AA, AB, ... AZ, BA, ...).

My try was this:

excel_letters <- LETTERS

for(n in length(LETTERS)){

  excel_letters <- c(excel_letters, paste0(LETTERS[n], LETTERS))

}

Since i am defining excel_letters outside of the loop before iterating through the loop, i expected to get the wanted output. Instead i am only getting:

 [1] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"  "K"  "L"  "M"  "N"  "O"  "P"  "Q"  "R"  "S"  "T"  "U"  "V"  "W"  "X"  "Y"  "Z"  "ZA" "ZB" "ZC"
[30] "ZD" "ZE" "ZF" "ZG" "ZH" "ZI" "ZJ" "ZK" "ZL" "ZM" "ZN" "ZO" "ZP" "ZQ" "ZR" "ZS" "ZT" "ZU" "ZV" "ZW" "ZX" "ZY" "ZZ"

Which is basically LETTERS plus the last iteration.

What am i missing here?

I know there are other approaches to this but i wanna know why this specifically doesn't work.


Solution

  • As mentioned, length(LETTERS) is a single element, so for (n in length(LETTERS)) iterates over a single value.

    In general you rarely need to iterate over indices — it’s easier to iterate over the values in your vector directly:

    for (letter in LETTERS) …
    

    In the rare event where you really need to iterate over the indices of a vector (which you don’t need here), use the pattern

    for (i in seq_along(the_vector))
    

    … but for your use-case, a better (shorter, more expressive, more efficient) solution avoids the loop entirely, in favour of direct construction:

    excel_letters <- paste0(rep(c("", LETTERS), each = length(LETTERS)), LETTERS)
    

    The more you write R the more you will discover how vectorisation and bespoke algorithms allow you to avoid loops.