sample in Rcpp Armadillo

心不动则不痛 提交于 2021-01-27 21:30:25

问题


I am currently struggeling with the sample() command provided in RcppArmadillo. When I try to run the code below I get the error no matching function for call to sample and I already add the extra Rcpp:: namespace in front since this worked out well in another post.

I also tried several other container classes, but I am always stuck with this error. Below is some code, which produces the error.

Any help would be greatly appreciated :)

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadilloExtensions/sample.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericMatrix example(arma::mat fprob,
                      int K) {
  int t = fprob.n_rows;
  IntegerVector choice_set = seq_len(K);
  arma::mat states(t,1); states.fill(0);
  arma::rowvec p0(K);
  arma::rowvec alph(K);
  double fit;

  p0 = fprob.row(t-1);
  fit = accu(p0);
  alph = p0/fit;
  states(t-1,1) = Rcpp::RcppArmadillo::sample(choice_set, 1, false, alph)[0];

  return wrap(states);
}


回答1:


Here the definition of that function from the header:

    // Enables supplying an arma probability
    template <class T> 
    T sample(const T &x, const int size, const bool replace, arma::vec &prob_){
      return sample_main(x, size, replace, prob_);
    }

Note that it expects a arma::vec == arma::colvec, while you are providing a arma::rowvec. So it should work if you change p0 and alph to arma::vec. Untested because of missing sample data ...

BTW, there is meanwhile also a Rcpp:::sample() function in case you are not really needing Armadillo for other tasks.

Concerning the performance questions raised by @JosephWood in the comments: I have the impression that both Rcpp::sample() and Rcpp::RcppArmadillo::sample() are based on do_sample(). So they should be quite similar in most cases, but I have not benchmarked them. The higher performance of R for unweighted sampling without replacement for larger numbers comes from the hash algorithm, which is selected at R level in such cases. It is also interesting to note that R 3.6 will have a new method for sampling in order to remove a bias present in the current method.



来源:https://stackoverflow.com/questions/54951791/sample-in-rcpp-armadillo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!