Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a boolean R vector to C dynamic_bitset

Tags:

c++

r

rcpp

What is the best way to pass an R vector of booleans to a C++ dynamic_bitset vector? Is there a way to use a pointer and the vector length to construct a dynamic_bitset object as would be possible for the vector class? Would you recommend using Rcpp ?
Thanks for your help and time...

like image 623
Stefan Bonn Avatar asked Nov 02 '22 17:11

Stefan Bonn


1 Answers

I would just create the dynamic_bitset like this:

#include <Rcpp.h>
#include <boost/dynamic_bitset.hpp>

using namespace Rcpp ;

// [[Rcpp::export]]
void create_dynamic_bitset( LogicalVector x ){  
    int n = x.size() ;
    boost::dynamic_bitset<> bs(n);
    for( int i=0; i<n; i++) bs[i] = x[i] ;

    // do something with the bitset
    for (boost::dynamic_bitset<>::size_type i = 0; i < x.size(); ++i)
        Rcout << x[i];
    Rcout << "\n";

}

Internally, R logical vectors are just int arrays. So there is not a more direct way to construct the dynamic_bitset, you have to iterate.

Also, beware of missing values in your input LogicalVector.

Alternatively, you might have the input data stored as a raw vector (Rcpp class RawVector), use a dynamic_bitset<Rbyte> and use the block constructor:

void create_dynamic_bitset( RawVector x ){  
    boost::dynamic_bitset<Rbyte> bs(x.begin(), x.end());
}
like image 177
Romain Francois Avatar answered Nov 15 '22 05:11

Romain Francois