犰狳矢量类上的RcppArmadillo样本 [英] RcppArmadillo sample on armadillo vector classes
问题描述
我们一直在使用RcppArmadillo
中的sample
函数来随机采样NumericVector
对象.但是,我们注意到无法在Armadillo类型(vec
或uvec
)上使用相同的功能.我们已经查看了sample.h
文件中的函数定义,它看起来像应该可以使用这些类型的模板化函数,但是我们无法弄清楚如何使其与Armadillo类一起使用Rcpp
库中NumericVector
或IntegerVector
类型之间的大量转换.
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.
例如,我们将此功能编写在名为try.cpp
的文件中.
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 :)
推荐答案
万一将来有人遇到此问题,该问题似乎与所使用的命名空间中sample
函数的多个定义有关.专门输入定义了所需功能的名称空间即可解决此问题.特别是,需要从Rcpp::RcppArmadillo
调用sample
函数.
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;
}
这篇关于犰狳矢量类上的RcppArmadillo样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!