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 in R comparison

The following piece of code does exactly what I need. However, for exercise purposes, I cannot use the rep function.

for (i in 1:4){
  print(paste(rep(LETTERS[i], i), collapse = ""))
}
  • [1] "A"
  • [1] "BB"
  • [1] "CCC"
  • [1] "DDDD"

So I attempted the following:

for (i in 1:4) {
  for (j in 1:i) {
    print(paste(LETTERS[i]))
  }
  cat('\n')
}
  • [1] "A"

    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] "B"

  • [1] "B"

  • [1] "C"

  • [1] "C"

  • [1] "C"

  • [1] "D"

  • [1] "D"

  • [1] "D"

  • [1] "D"

which isn’t quite the output that I’m going for. I tried transposing within the inner for loop all to no avail. Can someone please help here?

>Solution :

One potential solution would be to add each letter to a vector then print the vector after each "j" loop and clear the vector, e.g.

output <- c()
for (i in 1:4) {
  for (j in 1:i) {
   output <- paste0(output, LETTERS[i])
  }
  print(output)
  output <- c()
}
#> [1] "A"
#> [1] "BB"
#> [1] "CCC"
#> [1] "DDDD"

Created on 2023-06-28 with reprex v2.0.2

Edit

Per @thelatemail’s comment, you should avoid ‘growing’ a vector in the ‘lazy’ way I suggested above, as performance is terrible. A much better option is to pre-allocate the vector then fill it, with letters and collapse the output e.g.

for (i in 1:4) {
  out <- vector("character", i)
  for (j in 1:i) {
    out[j] <- LETTERS[i]
  }
  print(paste(out, collapse=""))
}
#> [1] "A"
#> [1] "BB"
#> [1] "CCC"
#> [1] "DDDD"

Created on 2023-06-28 with reprex v2.0.2

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