Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how create a sequence of strings with different numbers in R

Tags:

r

sequence

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.

Thanks in advance.

like image 860
Agus camacho Avatar asked Feb 29 '16 23:02

Agus camacho


People also ask

How do I make a list of strings in R?

How to Create Lists in R? We can use the list() function to create a list. Another way to create a list is to use the c() function. The c() function coerces elements into the same type, so, if there is a list amongst the elements, then all elements are turned into components of a list.

Which function is used to generate sequence of numbers R?

Seq(): The seq function in R can generate the general or regular sequences from the given inputs.


2 Answers

The sprintf function should also work:

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:

rasters <- sprintf("raster[%d]",seq(1:99))
like image 107
Abdou Avatar answered Oct 08 '22 05:10

Abdou


We can do

paste0("raster[", 1:6, "]")
# [1] "raster[1]" "raster[2]" "raster[3]" "raster[4]" "raster[5]" "raster[6]"
like image 44
SymbolixAU Avatar answered Oct 08 '22 06:10

SymbolixAU