tsinghsia
tsinghsia

Reputation: 21

How to use Rcpp sugar function(mean,var) with vector<double>?

vector<double> Stock::getReturns(unsigned n){
vector<double> returnSelect;
for (int i=0;i<n;i++)
    returnSelect.push_back(returns[i]);
return returnSelect;
}

double Stock::getMeanReturn(unsigned n){
double m=0;
vector<double> vec=getReturns(n);
for (int i=0;i<n;i++){
    m+=vec[i];
}
m=m/n;
return m;
};

These code with vector<double> works perfectly, but when I replace vector<double> with NumericVector, I could build the code in Eclipse, but it crashed when I ran it. NumericVector seems to be the problem.

Rcpp::NumericVector Stock::getReturns(unsigned n){
Rcpp::NumericVector returnSelect;
for (int i=0;i<n;i++)
    returnSelect.push_back(returns[i]);
return returnSelect;
}

double Stock::getMeanReturn(unsigned n){
double m;
Rcpp::NumericVector vec=getReturns(n);
m=mean(vec);
return m;
};

So the question is why Eclipse can't deal with NumericVector? and is there any other method to use the Rcpp sugar if it doesn't take NumericVector?

Thanks!

Upvotes: 1

Views: 995

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368261

A few things:

  1. First off, Rcpp sugar works only on Rcpp types as all these sugar functions are explicitly programmed -- and they are programmed for R types in their Rcpp presentation.

  2. Second, your initial example is wrong. You cannot do m+=vec[i]; without having vec defined/declared somewhere. What is its size? Is the space reserved? I think you got lucky there.

  3. Third, please just don't state 'it crashed' without a reproducible example.

  4. Eclipse has nothing to do with it, but you may have set your environment up the wrong way.

Upvotes: 1

Related Questions