title: Reproducing R rep with the times argument in C++ and Rcpp
body: <p>I'm learning to use Rcpp. I'd like to use C++ to replicate the <code>rep</code> function in R. Rcpp includes several sugar functions that correspond to <code>rep</code> in R. (see bottom of page 3 at: <a href="http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-quickref.pdf" rel="nofollow">http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-quickref.pdf</a>. As I understand the documentation, the sugar functions <code>rep</code>, <code>rep_each</code>, and <code>rep_len</code> take two arguments -- a vector and an integer. However, what I would like to do is replicate the functionality of <code>rep</code> in R when I use the <code>times</code> argument. In that case, you can supply two vectors. A quick example in R:</p>
  
  <pre><code>x &lt;- c(10, 5, 12)
  y &lt;- c(2, 6, 3)
  
  rep(x, times = y)
  [1] 10 10  5  5  5  5  5  5 12 12 12
  </code></pre>
  
  <p>Thus <code>rep</code> with the <code>times</code> argument replicates each element of <code>x</code> as many times as the corresponding <code>y</code> value. As I understand it, I can't see any way to use the Rcpp sugar functions for this.</p>
  
  <p>I have created the following C++ function that works:</p>
  
  <pre><code>// [[Rcpp::export]]
  NumericVector reptest(NumericVector x, NumericVector y) {
      int n = y.size();
      NumericVector myvector(sum(y));
      int ind = 0;
      for (int i = 0; i &lt; n; ++i) {
          for (int j = 0; j &lt; y(i); ++j) {
              myvector(ind) = x[i];
              ind = ind + 1;
              }
          }
      return myvector;
  }
  
  x &lt;- c(10, 5, 12)
  y &lt;- c(2, 6, 3)
  
  reptest(x, y)
  [1] 10 10  5  5  5  5  5  5 12 12 12
  </code></pre>
  
  <p>It is a bit slower than <code>rep</code> in R. I am wondering if there is anyway to speed this up or if anyone has a better idea. As I understand it, <code>rep</code> is calling C code, so maybe it will be near impossible to improve upon <code>rep</code>. My goal is to speed up an MCMC loop (that uses the <code>rep</code> function) that takes a lot of time to run in R, so any speedup would be useful. Other parts of the MCMC loop are the slow parts, not <code>rep</code>, but I need the same functionality in my loop.</p>