[Rcpp-devel] Could Rcpp class(like NumericVector) be implemented in c++?

Qing Xia xiaqing.cufe at gmail.com
Sun May 26 19:23:45 CEST 2013


Dear All,

I tried to use NumericVector in class declaration, Eclipse could compile
the code, but could not run it (something to do with the R.dll). I tried
replacing NumericVector with vector<double> and it worked with no
problem. I want to use NumericVector so that I could use Rcpp sugar to
compute the mean and variance. Could it possibly I get it wrong that sugar
only take NumericVector?

I have configured Eclipse and I could ran the codes in the example folder
perfectly. I've attached simplified version of my code. Any hints please?
I've been stuck on this.

Thanks!

Qing

#include<Rcpp.h>
using namespace Rcpp;

class Stock{
private:
NumericVector prices;
NumericVector returns;
void calcReturns();
public:
void loadPricesFromFile(const char *symbol);
NumericVector getReturns(unsigned);
NumericVector getPrices(unsigned);
double getMeanReturn(unsigned);
double getReturnStdDev(unsigned);
void plotHistory(unsigned);
};

void Stock::calcReturns(){
for (int i=0;i<prices.size()-1;i++){
returns.push_back(log(prices[i]/prices[i+1]));
}
};

NumericVector Stock::getPrices(unsigned n){
NumericVector vec(n);
for (int i=0;i<vec.size();i++){
vec.push_back(prices[i]);
}
return vec;
}

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

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

double Stock::getReturnStdDev(unsigned n){
NumericVector vec(n);
vec=getReturns(n);
double m=var(vec);
return m;
}

void Stock::plotHistory(unsigned n){

}

void Stock::loadPricesFromFile(const char *symbol){
for (int i=0;i<1000;i++){
prices.push_back(1000-i);
}
calcReturns();
}

int main(int argc,char *argv[]){
Stock stock;
stock.loadPricesFromFile("MSFT");
    double m,sd;
    unsigned num;
    std::cout<<"Please enter the number for computation:";
    std::cin>>num;
    m=stock.getMeanReturn(num);
    sd=stock.getReturnStdDev(num);
    std::cout<<m<<"\t"<<sd<<std::endl;
    return 0;
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130526/f20eef55/attachment-0001.html>


More information about the Rcpp-devel mailing list