rrep

How to interchange a fixed string with sequential string in R?


How do I interchange a fixed string with a sequential string?

For instance, if I want to repeat a pattern of a string, I would do the following:

> rep(c("Filler","Model"),2)
[1] "Filler" "Model"  "Filler" "Model"  "Filler" "Model" 

But, I want something like this where I can automatically add numbers behind "Model" with each iteration of a repeat:

[1] "Filler" "Model 1" "Filler" "Model 2" "Filler" "Model 3"

Is there a way to combine rep() with sprintf()?


Solution

  • Here is one base R approach. We can access all even elements of the input vector and then paste with a numeric sequence.

    x <- rep(c("Filler","Model"),3)
    x[c(FALSE, TRUE)] <- paste(x[c(FALSE, TRUE)], c(1:3))
    x
    
    [1] "Filler" "Model 1" "Filler" "Model 2" "Filler" "Model 3"