4

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.

4

2 回答 2

2

我们不需要一个循环,因为它paste是矢量化的。所以要么使用sprintf

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

或者paste

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

如果这是一个for循环练习,则初始化“Names”向量并将“Names”的每个元素分配给从paste

Names <- character(length(x))
for(i in seq_along(x)){
  Names[i] <- paste0("A_", i, ".png") 
}
于 2016-11-06T14:39:16.533 回答
1

stringi解决方案:

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

使用从 1 到 200 的向量和“.png”粘贴“A_”。矢量化可以提供帮助,我们得到了预期的结果。

于 2017-02-17T22:33:54.970 回答