[Rcpp-devel] Incorrect results from RcppArmadillo::sample

Shuai Wang wangshuai901 at gmail.com
Sun Oct 18 18:13:11 CEST 2015


Dear list,


I am a newbie to rcpp and currently I am trying to translate some R code
into C++ code.

In particular, when I was trying to translate the following R code into C++
code:

    *Z[i] <- sample(15, 1, replace = FALSE, prob = (exp(prob - deno)))*

I found some errors in my C code, which troubles me a lot.

Let's elaborate a little bit.

I found that Rcpp does not provide a *sample* function, so I follow the
instructions here
<http://gallery.rcpp.org/articles/using-the-Rcpp-based-sample-implementation/>
to use
*RcppArmadillo::sample.*

However, even though the first parameter of *sample* function in R can be a
integer:

    function (x, size, replace = FALSE, prob = NULL)
    {
      *  if (length(x) == 1L && is.numeric(x) && x >= 1) {*
*            if (missing(size)) *
*                size <- x*
           * sample.int <http://sample.int>(x, size, replace, prob)*
        }
        else {
            if (missing(size))
                size <- length(x)
            x[sample.int(length(x), size, replace, prob)]
        }
    }

I figure out that the first parameter of *RcppArmadillo::sample *cannot be
a integer, it only accepts
a vector. So given my R code, I translate it into the following C code.

   *     Rcpp:NumericVector JJ(15);*
*        JJ[0] = 15;*

*        Z[i-1] = RcppArmadillo::sample(JJ, 1, false, (exp(prob -
deno)))[0];*


Then I found some errors in the above code, say, while in the original R
code, Z[i] is a random number *between 1 and 15*, in the above C code,
Z[i-1] is *either 0 or 15*.

Am I clear? Could anyone give me some help on this issue? Thank you a lot!


Shuai
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20151018/7de886d6/attachment.html>


More information about the Rcpp-devel mailing list