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"

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

Leave a Reply