23

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.

2
  • 3
    Why doesn't it work? Post your reproducible attempts so we can help you. If you are constructing code with strings for later evaluation, that's the wrong way to do things. Commented Mar 1, 2016 at 0:03
  • You can consider looking at answers here for nice discussion and alternatives stackoverflow.com/questions/5812493/… Commented Jan 28, 2017 at 13:18

2 Answers 2

34

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))
Sign up to request clarification or add additional context in comments.

8 Comments

%d might b more appropriate. I think with %s, the sequence is being coerced to character first and then applied. But I could be wrong.
@RichardScriven, you're on to something. The usage of %s definitely makes R coerce the digits into characters. So, %d is more efficient. I will add it to the solution. Thanks!
Hate to comment on this but i have the opposite problem where "Ballroom 2-4" would ideally become "Ballroom 2, Ballroom 3, Ballroom 4". Can anyone help me with this ? I already asked the question a couple of days ago on stackoverflow (still waiting for a suggestion)
@KarimKardous, you may be looking for paste0(sprintf('Ballroom %d', 1:4), collapse = ", ").
Yes your answer makes sense, is there a DYNAMIC way of coding this ? what if the next row's value (it's a dataframe) is "Ballroom 5-8" ?
|
20

We can do

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

3 Comments

thanks for both answers! both work for me. It is a pity I could not decide which is best, so i just tossed a coin to choose one, though it should be best if at least someone has the mark. I up voted both, though.
@Aguscamacho no problem; there's usually more than one way to solve a problem. I wasn't aware of the sprintf method either so I've learnt something too.
@Aguscamacho, I think paste0 is syntactically better than sprintf as it's easier to guess what the function aims to achieve just by looking at its name?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.