简体   繁体   English

如何在R中创建具有不同数字的字符串序列

[英]how create a sequence of strings with different numbers in R

I just cant figure it out how to create a vector in which the strings are constant but the numbers are not.我只是不知道如何创建一个向量,其中字符串是常量但数字不是。 For example:例如:

c("raster[1]","raster[2]","raster[3]")

I'd like to use something like seq(raster[1],raster[99], by=1) , but this does not work.我想使用类似seq(raster[1],raster[99], by=1) ,但这不起作用。

Thanks in advance.提前致谢。

The sprintf function should also work: sprintf函数也应该可以工作:

rasters <- sprintf("raster[%s]",seq(1:99))
head(rasters)
[1] "raster[1]" "raster[2]" "raster[3]" "raster[4]" "raster[5]" "raster[6]"

As suggested by Richard Scriven, %d is more efficient than %s .正如 Richard Scriven 所建议的, %d%s更有效。 So, if you were working with a longer sequence, it would be more appropriate to use:因此,如果您正在处理更长的序列,则使用以下命令会更合适:

rasters <- sprintf("raster[%d]",seq(1:99))

We can do我们可以做的

paste0("raster[", 1:6, "]")
# [1] "raster[1]" "raster[2]" "raster[3]" "raster[4]" "raster[5]" "raster[6]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM