Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat a String N times in R?

Tags:

string

r

repeat

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?

like image 568
Marsellus Wallace Avatar asked Mar 12 '14 17:03

Marsellus Wallace


People also ask

How do you repeat a character in python?

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.

How do you repeat a string in C#?

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.


2 Answers

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" 
like image 86
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 08 '22 00:10

A5C1D2H2I1M1N2O1R2T1


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" 
like image 41
akrun Avatar answered Oct 08 '22 02:10

akrun