[Rcpp-devel] NA_REAL in RcppParallel
Jason Foster
jason.j.foster at gmail.com
Thu Jun 2 13:07:43 CEST 2016
Hi,
My question is how can I return a thread safe NA_REAL using RcppParallel?
I've read many posts about how it's not thread safe to call R or Rcpp APIs
when using RcppParallel (
http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2016-January/009061.html),
so in the past I've played it safe by returning NAN in C++ instead (as it's
my understanding NA_REAL is specific to R).
The following example is a modified version of "Transforming a Matrix in
Parallel using RcppParallel" (
http://gallery.rcpp.org/articles/parallel-matrix-transform/) that checks
whether the input value is NA before taking the sqrt, otherwise NA is
returned (note: this is the desired behavior and for illustrative purposes
only):
// [[Rcpp::depends(RcppParallel)]]
#include <Rcpp.h>
#include <RcppParallel.h>
using namespace Rcpp;
using namespace RcppParallel;
struct SquareRoot : public Worker
{
// source vector
const RVector<double> input;
// destination vector
RVector<double> output;
// initialize with source and destination
SquareRoot(const NumericVector input, NumericVector output)
: input(input), output(output) {}
// take the square root of the range of elements requested
void operator()(std::size_t begin, std::size_t end) {
for (std::size_t i = begin; i < end; i++) {
if (std::isnan(input[i])) {
output[i] = NA_REAL; // this is the desired output (instead of NAN)
} else {
output[i] = sqrt(input[i]);
}
}
}
};
// [[Rcpp::export]]
NumericVector parallelVectorSqrt(NumericVector x) {
// allocate the output vector
NumericVector output(x.size());
// SquareRoot functor (pass input and output vectors)
SquareRoot squareRoot(x, output);
// call parallelFor to do the work
parallelFor(0, x.size(), squareRoot);
// return the output vector
return output;
}
Any guidance or insight would be much appreciated. Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20160602/39b7324e/attachment.html>
More information about the Rcpp-devel
mailing list