How to use paste with for-loops?

dede picture dede · Nov 6, 2016 · Viewed 8.9k times · Source

I am trying to use the function stri_join, from the library stringi in a loop, but I am having difficulties. I would like to obtain "A_1.png", "A_2.png", "A_3.png", "A_4.png", "A_5.png", and so on until "A_200.png".

Here is my attempt:

 x <- c(1:200)
 x
 for (i in 1:length(x)){
   Names <-paste("A_", 1:length(i), ".png",sep = "")
   print(Names)
 }

I obtain "A_1.png" 200 times. If you could point what I am missing.

Answer

akrun picture akrun · Nov 6, 2016

We don't need a loop for this as paste is vectorized. So either use sprintf

Names <- sprintf("A_%d.png", x)

Or paste

Names <- paste0("A_", x, ".png")

If this is an exercise on for loop, initialize the 'Names' vector and assign each element of 'Names' to the corresponding value from paste

Names <- character(length(x))
for(i in seq_along(x)){
  Names[i] <- paste0("A_", i, ".png") 
}