title: R dplyr repeat dataframe rows by group
body: <p>I have a dataframe containing groups. One column <code>ntimes</code> indicates, how many times the group should be repeated, keeping same row order. 
  I want extend my dataframe by groups of rows, repeated several times. Howevere, I am not sure how to make it in efficient way?</p>
  
  <p>My example:</p>
  
  <pre><code>  # Repeat rows by group
  set.seed(5)
  df &lt;- data.frame(my.group = rep(c("a", "b", "z"), each = 3),
                   vals = runif(9),
                   ntimes = c(3,3,3, 1,1,1,2,2,2))
  
    my.group      vals ntimes
  1        a 0.1104530      3
  2        a 0.2732849      3
  3        a 0.4905132      3
  4        b 0.3184040      1
  5        b 0.5591728      1
  6        b 0.2625931      1
  7        z 0.2018752      2
  8        z 0.3875257      2
  9        z 0.8878698      2
  </code></pre>
  
  <p>Group <code>a</code> should be repeated 3 times, group <code>b</code> one time, group <code>z</code> 3 times.</p>
  
  <p>Expected output:</p>
  
  <pre><code>  my.group      vals ntimes
  1        a 0.1104530      3
  2        a 0.2732849      3
  3        a 0.4905132      3
  4        a 0.1104530      3
  5        a 0.2732849      3
  6        a 0.4905132      3
  7        a 0.1104530      3
  8        a 0.2732849      3
  9        a 0.4905132      3
  10       b 0.3184040      1
  11       b 0.5591728      1
  12       b 0.2625931      1
  13       z 0.2018752      2
  14       z 0.3875257      2
  15       z 0.8878698      2
  16       z 0.2018752      2
  17       z 0.3875257      2
  18       z 0.8878698      2
  </code></pre>
  
  <p>I have tried several approaches using <code>dplyr</code>, but neither of them produces desired outputs:</p>
  
  <pre><code># repeat df rows by group
  library(dplyr)
  df %&gt;% 
    group_by(my.group) %&gt;% 
    mutate(new = rep(seq_len(n()/2), each = 2, length.out = n()))
  
  
  df %&gt;% 
    group_by(my.group) %&gt;% 
    slice(rep(1:n(), each = 2))
  
  
  df %&gt;% 
    group_by(my.group) %&gt;% 
    mutate(count = c(3,1,2)) %&gt;% 
    expand(ntimes = seq(1:ntimes))
  </code></pre>
  
  <p>I highly appreciate any suggestions.</p>