Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading