How to repeat a String N times in R?

Marsellus Wallace picture Marsellus Wallace · Mar 12, 2014 · Viewed 71.6k times · Source

In Ruby I could repeat a String n times with the following:

E.G. "my_string" * 2 -> "my_stringmy_string"

Is there an equally simple way for doing this in R?

Answer

A5C1D2H2I1M1N2O1R2T1 picture A5C1D2H2I1M1N2O1R2T1 · Mar 12, 2014

You can use replicate or rep:

replicate(2, "my_string")
# [1] "my_string" "my_string"

rep("my_string", 2)
# [1] "my_string" "my_string"

paste will put it together:

paste(replicate(2, "my_string"), collapse = "")
# [1] "my_stringmy_string"