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

Rahel Sollmann rasrage at yahoo.de
Fri Oct 26 20:08:32 CEST 2012

Hi Rcpp folks;
I am very new to c++ so I apologize in advance if this is a stupid question:
For a larger analysis I am trying to implement the R function sample() in c++ via RcppArmadillo. I want to use the resulting vector as an index to access a matrix. A simple dummy example of what I am trying to do is below. By breaking the code into several pieces I have been able to determine that the problem lies with the vector produced by sample() ('guys' in the example below) and the way I am attempting to use it as an index for the matrix tmpMat. I have tried making 'um', 'unmarked' and 'guys' integers/IntegerVectors but that didn't resolve my problem either. 

The function compiles fine but when I run it in R I get this nondescript error message: 'Error in fun(y, n, J, lam, um) :'

Any help on this would be greatly appreciated.

y<-list(matrix(0, nrow=umn, ncol=J),matrix(0, nrow=umn, ncol=J),matrix(0, nrow=umn, ncol=J),
matrix(0, nrow=umn, ncol=J),matrix(0, nrow=umn, ncol=J) )
lam <-rep(0.3, umn)

code<-'Rcpp::Environment base("package:base");
Rcpp::Function sample = base["sample"];

Rcpp::List obs = y;
int ntraps = Rcpp::as<int>(J); 
int npics= Rcpp::as<int>(n);
arma::vec probs= Rcpp::as<arma::vec>(lam);
arma::vec unmarked = Rcpp::as<arma::vec>(um);
bool txtx = FALSE;

for (int t=0; t<5; t++ ) {
arma::mat tmpMat = Rcpp::as<arma::mat>(obs(t));

   for (int k=0; k<ntraps; k++ ) {

              probs= probs/sum(probs);
               arma::vec guys= Rcpp::as<arma::vec>(sample(unmarked, npics,_["replace"] = txtx, probs));
        for (int kk=0; kk<npics; kk++){

return Rcpp::wrap(obs);
fun<-cxxfunction(signature(y="list", J="integer",n="integer", lam="numeric",
             um="numeric"), body=code, plugin="RcppArmadillo"  )
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20121026/36c5aa3f/attachment.html>

More information about the Rcpp-devel mailing list