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?
In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times.
The Enumerable. Repeat() function of LINQ can be used to repeat a string to a specified number of times in C#. The Enumerable. Repeat() function takes two parameters, a string variable and the number of times that string variable must be repeated.
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"
With R 3.3.0
, we can use strrep
from base R
strrep("my_string",2) #[1] "my_stringmy_string"
We can also pass a vector of values in times
strrep("my_string",1:3) #[1] "my_string" "my_stringmy_string" #[3] "my_stringmy_stringmy_string"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With