如何在for循环中使用粘贴? [英] How to use paste with for-loops?

查看:72
本文介绍了如何在for循环中使用粘贴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图循环使用库 stringi 中的函数 stri_join ,但是遇到了困难.我想获得"A_1.png","A_2.png","A_3.png","A_4.png","A_5.png",依此类推,直到获得"A_200.png".

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

这是我的尝试:

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

我获得了"A_1.png"200次如果您能指出我所缺少的.

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

推荐答案

我们不需要循环,因为 paste 是矢量化的.因此,要么使用 sprintf

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

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

粘贴

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


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


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

这篇关于如何在for循环中使用粘贴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆