6

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.

leonheess
  • 16,068
  • 14
  • 77
  • 112
dede
  • 1,129
  • 5
  • 15
  • 35

2 Answers2

3

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") 
}
akrun
  • 874,273
  • 37
  • 540
  • 662
  • please can you give me a hint on how to attach the indices values in the out put if you have two for loops in r? res <- c() for (i in seq(1, 21, 2)) { for (j in seq(22, 30)) { model, how to attach the values of i and j in the output res <- c(res, model).. thanks! – Stackuser Mar 05 '20 at 16:30
  • @Stackuser I would return as a `list` if i understand your question – akrun Mar 05 '20 at 18:01
  • thanks! I just want to attach the indices value in the result like if i and j are equal to 1, I want to get like 1-1-output(number or anything), then 1-2-output, 1-3-output....... – Stackuser Mar 05 '20 at 18:30
1

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.

bartektartanus
  • 15,284
  • 6
  • 74
  • 102