[Rcpp-devel] problem with sample() implemented in Rcpp/RcppArmadillo

Christian Gunning xian at unm.edu
Sun Oct 28 10:28:10 CET 2012


On Sat, Oct 27, 2012 at 7:50 AM, Dirk Eddelbuettel <edd at debian.org> wrote:
>
>
> We make them look like STL containers by giving them begin(),
> end(), ... member functions but they are still R objects ("SEXP") underneath.
>
> That means in particular that the carefully crafted STL algos with their
> performance guarantees will NOT have these guarantees.

Ah.  Thanks for the clarification.

> Someone should sit down and write a C++ variant of sample for Rcpp.  Having a
> starting point would help, others can then tune.

I spent some time looking at this today.  Guidance/advice on the best
approach here?

Assuming we desire results identical to R sample(), the simple
approach is to follow do_sample in src/main/random.c.  The functions
we'd use are ProbSampleReplace, ProbSampleNoReplace, SampleReplace,
SampleNoReplace, and FixupProb.

Q1 -- Are there any immediate drawbacks to cloning-and-transposing
these functions straight from R core?

Q2 -- Given the above, is the following pseudo-code a reasonable
approach?  I'm uncertain about the templated instantiation of the
return object.

template <class T>
T sample( const T &x, unsigned int size, bool replace ) {
    // user's responsibility? // RNGScope scope;
    ans = Vector<T>(size);
    ans.index = IntegerVector(size);
    if ( replace ) {
        ... SampleReplace  ...
    } else {
        ... SampleNoReplace  ...
    }
    for (int ii = 0; ii<size; ii++ ) {
        ans[ii] = x[ ans.index[ii] ];
    }
}

T sample( const T &x, unsigned int size, bool replace,  const
NumericVector &probs ) {
    // user's responsibility? // RNGScope scope;
    ans = Vector<T>(size);
    ans.index = IntegerVector(size);
    ...FixupProb...
    if ( replace ) {
        ... ProbSampleReplace  ...
    } else {
        ... ProbSampleNoReplace  ...
    }
    for (int ii = 0; ii<size; ii++ ) {
        ans[ii] = x[ ans.index[ii] ];
    }
    return ans;
}

-Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!


More information about the Rcpp-devel mailing list