I'm quite a newbie to Rcpp and its functionalities, not to mention C++ per se, so this might probably seem trivial to the experts among you. However, there's no such thing as a stupid question, so anyway:
I was wondering if there was a method to address multiple elements of a NumericVector in C++ at once using indexing. To make the whole thing more clear, here's the R equivalent of what I'm trying to do:
# Initial vector
x <- 1:10
# Extract the 2nd, 5th and 8th element of the vector
x[c(2, 5, 8)]
[1] 2 5 8
This is what I got so far in the C++ function that I'm executing in R using sourceCpp. It works, but it seems quite inconvenient to me. Is there any easier way to achieve my goals?
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector subsetNumVec(NumericVector x, IntegerVector index) {
// Length of the index vector
int n = index.size();
// Initialize output vector
NumericVector out(n);
// Subtract 1 from index as C++ starts to count at 0
index = index - 1;
// Loop through index vector and extract values of x at the given positions
for (int i = 0; i < n; i++) {
out[i] = x[index[i]];
}
// Return output
return out;
}
/*** R
subsetNumVec(1:10, c(2, 5, 8))
*/
> subsetNumVec(1:10, c(2, 5, 8))
[1] 2 5 8
You can do this if you use Armadillo vectors, rather than Rcpp vectors.
The Rcpp Gallery has a post with a complete example: see in particular the second example. Your indexing entries have to be in a (unsigned) uvec or umat.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With