I am trying to use Rcpp to do some importance sampling. A pivotal step is to take the mean of the importance weights (in this problem). My programme is doing importance sampling for multiple independent variables at the same time, so the code works with matrices rather than vectors. Below is a minimal reproducible example, which is idealised version of what is supposed to happen:
library(Rcpp)
cppFunction('
NumericVector test(){
NumericMatrix Numerator(100, 10);
NumericMatrix Denominator(100, 10);
for(int i = 0; i < 100; i++){
Numerator(i,_) = log(runif(10));
Denominator(i,_) = log(runif(10));
}
return colMeans(exp(Numerator - Denominator));
}
')
test()
I get this error which I do not understand:
file17dd7b43bf04.cpp:16:10: error: no matching function for call to 'colMeans'
return colMeans(exp(Numerator - Denominator));
^~~~~~~~
/Library/Frameworks/R.framework/Versions/3.6/Resources/library/Rcpp/include/Rcpp/sugar/functions/rowSums.h:951:1: note: candidate template ignored: could not match 'MatrixBase' against 'Vectorized'
colMeans(const MatrixBase<RTYPE, NA, T>& x, bool na_rm = false) {
^
Superficially it looks like the compiler is trying to tell me it doesn't know what the function colMeans
is, but a) I know this is included in the syntactic sugar for at least Rcpp 1.0.3 and higher, and b) the secondary error seems to suggest I am feeding in an incorrect argument. I am sure I am just missing something simple, but I am unsure what.
Following @DirkEddelbuettel's suggestion, the following reconfiguration seems to make the compiler happy:
library(Rcpp)
cppFunction('
NumericVector test(){
NumericMatrix Numerator(100, 10);
NumericMatrix Denominator(100, 10);
NumericMatrix Ratio(100, 10);
for(int i = 0; i < 100; i++){
Numerator(i,_) = log(runif(10));
Denominator(i,_) = log(runif(10));
Ratio(i,_) = exp(Numerator(i,_) - Denominator(i, _));
}
return colMeans(Ratio);
}
')
test()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With