dede
dede

Reputation: 1171

How to use paste with 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)
 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.

Upvotes: 6

Views: 15402

Answers (2)

bartektartanus
bartektartanus

Reputation: 16080

stringi solution:

stri_paste("A_",1:200,".png")

Paste 'A_' with a vector from 1 to 200 and '.png'. Vectorization comes to help and we get the desired result.

Upvotes: 1

akrun
akrun

Reputation: 886948

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

Upvotes: 3

Related Questions