2

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()?

ssjjaca
  • 219
  • 1
  • 6

3 Answers3

3

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"
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Here is an alternative:

x <- rep(c("Filler","Model"),3)

x[x=="Model"] = paste("Model", seq_along(x[x=="Model"]))
x
[1] "Filler"  "Model 1" "Filler"  "Model 2" "Filler"  "Model 3"
TarJae
  • 72,363
  • 6
  • 19
  • 66
1

Here is another option if the Filler Model sequence is not always alternating:

x <- c("Filler", "Model", "Filler", "Model", "Model", "Model")

replace(x, which(x == "Model"), paste(x, cumsum(x == "Model"))[which(x == "Model")])
#> [1] "Filler"  "Model 1" "Filler"  "Model 2" "Model 3" "Model 4"

Or slightly more compact

paste(x, replace(cumsum(x == "Model"), which(x!="Model"), ""))
#> [1] "Filler " "Model 1" "Filler " "Model 2" "Model 3" "Model 4"
AndS.
  • 7,748
  • 2
  • 12
  • 17