[Rcpp-devel] R.e. Rcpp equivalent of sample()?
edd at debian.org
Sun May 15 02:55:29 CEST 2011
On 14 May 2011 at 19:41, Christian Gunning wrote:
| > In the Rcpp vignettes, I found some of the R-like functions for
| > sampling from distributions (runif, rnorm, etc), but I didn't see a function
| > mimicking sample(). I checked the list of unit tests and didn't see it there
| > either. Have I missed it? Is there a C++ function I should be using to
| > sample (with replacement in my particular situation) from a vector (with
| > provided weights).
| In the quickref (and introduction) vignette, there's an example of how
| to import a function from R and use it in C++.
| Honestly, I've found it easiest to just import sample() from R (in the
| stats namespace). Two things to note:
| 1. Performance -- there's a penalty for going back to R, but it's per
| function call. So, you can pull a vector result of sample into an
| integer vector.
| 2. I find it easiest to sample indices rather then elements of the
| set that I want to sample, and then do indexing within C++, for
| example with an STL style loop.
| I'm on the road now, but I can try to fire off an example in the next day or 2.
There is also Davor's trick of getting the C++ function pointer---this avoids
the 'going back to R' overhead. But it is not really clean to call an API
that way if the API decided to close off those access points....
(And before anyone asks: Davor's trick goes back to some work by Romain and
is for example used in the CRAN package rgam maintained by Davor; see its
src/loess.cpp. Calling a function from R via the Rcpp accessors is surely
easier, safer and better for beginners.)
Gauss once played himself in a zero-sum game and won $50.
-- #11 at http://www.gaussfacts.com
More information about the Rcpp-devel