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

时间:2022-08-31 22:53:48

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.

提前致谢。

2 个解决方案

#1


17  

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. So, if you were working with a longer sequence, it would be more appropriate to use:

正如Richard Scriven所建议的,%d比%s更有效。因此,如果您使用更长的序列,则使用更合适:

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

#2


10  

We can do

我们可以做的

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

#1


17  

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. So, if you were working with a longer sequence, it would be more appropriate to use:

正如Richard Scriven所建议的,%d比%s更有效。因此,如果您使用更长的序列,则使用更合适:

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

#2


10  

We can do

我们可以做的

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