user
user

Reputation: 1140

Repeated Rcpp NumericVector

I have a vector x from which I want to create a vector y consisting of multiple copies of x. So, if x is {1, 2, 3} and the number of repetitions n is 3, y would be {1, 2, 3, 1, 2, 3, 1, 2, 3}. x must either be a std::vector<double> or an Rcpp::NumericVector. y must be an Rcpp::NumericVector. I use C++20.

Of course, I could simply iterate over the elements like:

const int x_size = x.size();
Rcpp::NumericVector y (x_size * n);
for(int i = 0; i < n; ++i) {
  const int s = x_size * i;
  for(int j = 0; j < x_size; ++j) {
    y[s + j] = x[j];
  }
}

But I guess there is a better solution than such a nested loop.

Instead of creating y, I also considered dynamically resizing x to size x.size() * n and inserting multiple copies of itself, but did not find out how to do this with an Rcpp::NumericVector.

So, how do I create y from x and n?

Upvotes: 2

Views: 124

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368499

This already exists as Rcpp sugar function rep(x, n) modeled after the equivalent base R function.

Code

#include <Rcpp/Rcpp>

// [[Rcpp::export]]
Rcpp::NumericVector myrep(Rcpp::NumericVector x, int n) {
    return Rcpp::rep(x, n);
}

/*** R
x <- c(1, 2, 3, 4)
n <- 3
myrep(x, n)
*/

Output

> Rcpp::sourceCpp("answer.cpp")

> x <- c(1, 2, 3, 4)

> n <- 3

> myrep(x, n)
 [1] 1 2 3 4 1 2 3 4 1 2 3 4
> 

Discussion

You still may want to entertain writing such a function yourself. You have accessor size() and length() for the incoming vector, you have n and the rest are just two careful loops (in the simplest approach).

Upvotes: 4

Related Questions