Search code examples
rrcpprcpparmadillo

Subset vector by bool vector in Rcpp


I would like to subset a vector {1,2,3,4} with a bool vector. For instance, if my bool vector was {false,true,true,true}, I would like to get vector {2,3,4}. In regular R, I could do this with

    sample_states<-c(1:4)[c(a,b,c,d)]

where a,b,c,d are bools. My question is twofold: 1) How can I create a vector of bools using Armadillo/Rcpp, and 2) how can I use that vector to subset my vector {1,2,3,4}. Thank you in advance for your time.


Solution

  • Here two quick examples how to create a Rcpp::LogicalVector and subset another vector with it:

    #include <Rcpp.h>
    // [[Rcpp::plugins(cpp11)]]
    
    // [[Rcpp::export]]
    Rcpp::NumericVector subset1() {
      Rcpp::NumericVector in = {1.0, 2.0, 3.0, 4.0};
      Rcpp::LogicalVector mask = {false, true, true, true};
      return in[mask];
    }
    
    // [[Rcpp::export]]
    Rcpp::NumericVector subset2() {
      Rcpp::NumericVector in = Rcpp::runif(10);
      Rcpp::LogicalVector mask = in > 0.5;
      return in[mask];
    }
    
    /*** R
    subset1()
    set.seed(42)
    subset2()
    */
    

    The first example uses "braced initialization" from C++11 to quickly generate a LogicalVector. You could just as easily assign the values individually. The second example uses a logical expression to create a LogicalVector. In both cases, sub-setting looks very much like in R (thanks to Rcpp sugar).

    As Dirk said in the comments: there are more examples in the Rcpp gallery. Just search for 'indexing' or 'LogicalVector'.