[Rcpp-devel] Checking a condition like any(x < lowerBd)

Douglas Bates bates at stat.wisc.edu
Thu Jun 10 17:47:52 CEST 2010


I thought I had had enough coffee this morning not to make really dumb
mistakes but perhaps not.

I want to check that a particular NumericVector is within a feasible
region defined by lower and upper bounds on each element.  For the
lower bound I am checking for the equivalent of any(x < lowerBd) in R.
 I can do it in two stages, as in the enclosed chkfun2, but my attempt
to do this in a single operation using std::inner_product failed.  Can
anyone suggest why?

P.S. I used cxxfunction here because I couldn't find cppfunction in
either the inline or the Rcpp packages.  Again, am I missing
something?
-------------- next part --------------
library(Rcpp)
library(inline)
chkfun1 <- cxxfunction(signature(x = "numeric", lowerBd = "numeric"), '
       NumericVector xx(x), ll(lowerBd);
       if (xx.size() != ll.size()) return R_NilValue;
       LogicalVector ans(xx.size());
       std::transform(xx.begin(), xx.end(), ll.begin(), ans.begin(), std::less<double>());
       return ans;
', plugin = "Rcpp")

chkfun1(1, 0)
chkfun1(c(1, 0, 1), c(0, -Inf, 0))

chkfun2 <- cxxfunction(signature(x = "numeric", lowerBd = "numeric"), '
       NumericVector xx(x), ll(lowerBd);
       if (xx.size() != ll.size()) return R_NilValue;
       std::vector<bool> cmp(xx.size());
       std::transform(xx.begin(), xx.end(), ll.begin(), cmp.begin(), std::less<double>());
       return wrap(std::accumulate(cmp.begin(), cmp.end(), bool(), std::logical_or<bool>()));
', plugin = "Rcpp")
chkfun2(1, 0)
chkfun2(c(1, 0, 1), c(0, -Inf, 0))

chkfun3 <- cxxfunction(signature(x = "numeric", lowerBd = "numeric"), '
       NumericVector xx(x), ll(lowerBd);
       if (xx.size() != ll.size()) return R_NilValue;
       return wrap(std::inner_product(xx.begin(), xx.end(), ll.begin(),
                   bool(), std::less<double>(), std::logical_or<bool>()));
', plugin = "Rcpp")
chkfun3(1, 0)
chkfun3(c(1, 0, 1), c(0, -Inf, 0))

sessionInfo()
-------------- next part --------------
A non-text attachment was scrubbed...
Name: check.Rout
Type: application/octet-stream
Size: 2748 bytes
Desc: not available
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20100610/09c5f938/attachment.obj>


More information about the Rcpp-devel mailing list