2

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.

pestopasta
  • 51
  • 6
  • 2
    That is answered in posts on 'Indexing' at the [Rcpp Gallery](http://gallery.rcpp.org/) -- please read those. – Dirk Eddelbuettel Apr 13 '19 at 17:08
  • Thank you, I will read through more carefully. Is there anywhere in the Gallery I could look for creating a matrix and vector of bools? Thank you for your time. – pestopasta Apr 13 '19 at 17:16

1 Answers1

6

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'.

Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75