The original code is confused about where to use a vector, and where to use a scalar.
He is shorter and repaired version:
#include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
DataFrame cond(double epsil, int iNsim) {
double ans;
NumericVector vans(iNsim);
NumericVector vcond(iNsim);
RNGScope scope;
for (int i=0; i<iNsim; i++) {
ans = R::rnorm(0.0, 1.0);
vans[i] = ans;
if (fabs(ans) >= epsil) {
vcond[i] = 10;
} else {
vcond[i] = -10;
}
}
return DataFrame::create(_["sim"] = vans,
_["cond"] = vcond);
}
Besides using (and passing) scalars where scalars were meant to be used, it also corrects abs()
to fabs()
-- a common C/C++ problem. I also reverted to Rcpp vectors - as much as I like to use Armadillo, it wasn't needed here.
Here is example output given a random seed:
R> sourceCpp("/tmp/erlis.cpp")
R> set.seed(1)
R> cond(1.0, 6)
sim cond
1 -0.626454 -10
2 0.183643 -10
3 -0.835629 -10
4 1.595281 10
5 0.329508 -10
6 -0.820468 -10
R>