dede dede - 2 months ago 37
R Question

how to use paste in for loops

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)
for (i in 1:length(x)){
Names <-paste("A_", 1:length(i), ".png",sep = "")

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


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")