Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 [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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading