RcppArmadillo sample on armadillo vector classes

蓝咒 提交于 2019-12-18 09:47:16

问题


We have been using the sample function from RcppArmadillo to randomly sample a NumericVector object. However, we have noticed that it isn't possible to use the same function on Armadillo types (vec or uvec). We have looked at the function definitions from the sample.h file and it looks like a templated function that should be able to work with these types, but we haven't been able to figure out how to make it work with Armadillo classes without doing a lot of conversions to and from the NumericVector or IntegerVector types from the Rcpp library.

For example, we have this function written in a file called try.cpp.

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

using namespace arma;
using namespace Rcpp;

// [[Rcpp::export]]
arma::uvec sample_index(const int &size){
    arma::uvec sequence = linspace<uvec>(0, size-1, size);
    arma::uvec out = sample(sequence, size, false);
    return out;
}

Running the code above yields the following errors:

src/try.cpp|11 col 22 error| no matching function for call to 'sample' [cpp/gcc]      

~/Library/R/3.3/library/Rcpp/include/Rcpp/sugar/functions/sample.h|401 col 1 error| note: candidate function not viable: no known conversion from 'arma::uvec' (aka 'Col<unsigned int>') to 'int' for 1st argument [cpp/gcc]

~/Library/R/3.3/library/Rcpp/include/Rcpp/sugar/functions/sample.h|437 col 1 error| note: candidate template ignored: could not match 'Vector' against 'Col' [cpp/gcc]

Any help on this would be greatly appreciated :)


回答1:


In case anyone runs into this problem in the future, the problem seems to have something to do with multiple definitions of the sample function in the namespaces being used. Specifically typing out the namespaces where the required function is defined solves the problem. In particular, the sample function needs to be called from Rcpp::RcppArmadillo.

The following code works as desired.

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

// [[Rcpp::export]]
arma::uvec sample_index(const int &size){
    arma::uvec sequence = arma::linspace<arma::uvec>(0, size-1, size);
    arma::uvec out = Rcpp::RcppArmadillo::sample(sequence, size, false);
    return out;
}


来源:https://stackoverflow.com/questions/43353109/rcpparmadillo-sample-on-armadillo-vector-classes

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