75

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?

Henrik
  • 65,555
  • 14
  • 143
  • 159
Marsellus Wallace
  • 17,991
  • 25
  • 90
  • 154

4 Answers4

89

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"
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
75

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"
akrun
  • 874,273
  • 37
  • 540
  • 662
21

Use stri_dup function from stringi package

stri_dup("abc",3)
[1] "abcabcabc"

It is also vectorized, so you can do this:

> stri_dup(letters[1:3],4)
[1] "aaaa" "bbbb" "cccc"

Performance comparision :)

> microbenchmark(stri_dup("abc",3),paste(replicate(3, "abc"), collapse = ""))
Unit: microseconds
                                      expr    min     lq  median     uq     max neval
                        stri_dup("abc", 3)  2.362  3.456  7.0030  7.853  64.071   100
 paste(replicate(3, "abc"), collapse = "") 57.131 61.998 65.2165 68.017 200.626   100

> microbenchmark(stri_dup("abc",300),paste(replicate(300, "abc"), collapse = ""))
    Unit: microseconds
                                            expr     min       lq   median      uq     max neval
                            stri_dup("abc", 300)   6.441   7.6995  10.2990  13.757  45.784   100
     paste(replicate(300, "abc"), collapse = "") 390.137 419.7740 440.5345 460.042 573.975   100
bartektartanus
  • 15,284
  • 6
  • 74
  • 102
  • 2
    I'm not able to detect the microseconds differences while I wait for my fingers to plan the next line I'm going to be typing, but +1 for the alternatives. I've seen this package before but haven't used it yet. – A5C1D2H2I1M1N2O1R2T1 Mar 14 '14 at 13:30
  • 8
    But if you have to use this function like 1000 times it makes a difference, doesn't it? :) – bartektartanus Mar 14 '14 at 13:32
4

The stringr library offers the function str_dup():

str_dup("my_string", 2)

[1] "my_stringmy_string"

And it is vectorized over strings and times:

str_dup(c("A", "B", "C"), 2:4)

[1] "AA"   "BBB"  "CCCC"
tmfmnk
  • 38,881
  • 4
  • 47
  • 67