r - How to extract multiple values from a NumericVector in C++ -


i'm quite newbie rcpp , functionalities, not mention c++ per se, might seem trivial experts among you. however, there's no such thing stupid question, anyway:

i wondering if there method address multiple elements of numericvector in c++ @ once using indexing. make whole thing more clear, here's r equivalent of i'm trying do:

# initial vector x <- 1:10  # extract 2nd, 5th , 8th element of vector x[c(2, 5, 8)] [1] 2 5 8 

this got far in c++ function i'm executing in r using sourcecpp. works, seems quite inconvenient me. there easier way achieve goals?

#include <rcpp.h> using namespace rcpp;  // [[rcpp::export]] numericvector subsetnumvec(numericvector x, integervector index) {     // length of index vector   int n = index.size();   // initialize output vector   numericvector out(n);    // subtract 1 index c++ starts count @ 0   index = index - 1;    // loop through index vector , extract values of x @ given positions   (int = 0; < 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 if use armadillo vectors, rather rcpp vectors.

the rcpp gallery has post complete example: see in particular second example. indexing entries have in (unsigned) uvec or umat.


Comments