سؤال

I have a problem with run a following Rcpp function code originally written in C++ with following errors.

 > sourceCpp("MovingAverage2.cpp",showOutput = TRUE)

 Warning message:
 running command 'make -f "C:/PROGRA~1/R/R-31~1.0/etc/x64/Makeconf" -f
 "C:/PROGRA~1/R/R-31~1.0/share/make/winshlib.mk" SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)'
 SHLIB_LD='$(SHLIB_CXXLD)' SHLIB="sourceCpp_59566.dll" WIN=64 TCLBIN=64
 OBJECTS="MovingAverage2.o"' had status 2 
 Error in sourceCpp("MovingAverage2.cpp", showOutput = TRUE) : 
 Error 1 occurred building shared library.
 > 
 >t=250;nslow=20;nfast=5;d=2;Prices=rnorm(100)
 > MovingAverage2(t,nslow,nfast,d,Prices) 
 Error: could not find function "MovingAverage2" 

I guess original C++ has pointer (*Prices in below C++ code) variable but I have no idea how to manage the class so that Rccp can understand my code.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]

double Average(NumericVector Array, long t_begin, long t_end) {
    double mu=0;
    for(long t=t_begin; t<=t_end; t++)
       mu+=Array[t];
    return mu/(t_end-t_begin+1);
}

int MovingAverage2(long t, int nslow, int nfast, int d, double *Prices) {
//two MAs, time delay
   int S=1;
   int i=0;
   double slow_avrg;
   double fast_avrg;
   while(i<d && S!=0){
      slow_avrg=Average(Prices, t-nslow+1-i, t-i);
      fast_avrg=Average(Prices, t-nfast+1-i, t-i);
      if(i==0 && fast_avrg>slow_avrg)
        S=1;
    else if(i==0 && fast_avrg<=slow_avrg)
        S=-1;
    else if((fast_avrg>slow_avrg && S==-1) || (fast_avrg<=slow_avrg && S==1))
        S=0;
    i++;
  }
  return S;
}    

Could you let me know how to solve this pointer issue on my Rcpp code please.

هل كانت مفيدة؟

المحلول

The MovingAverage2 function is not Rcpp::exported so you cannot call it from the R side. Even though, Rcpp will not know what to do with a pointer double*, you should directly pass it down as a NumericVector :

// [[Rcpp::export]]
int MovingAverage2(long t, int nslow, int nfast, int d, NumericVector Prices) { 
   ...
   slow_avrg=Average(Prices, t-nslow+1-i, t-i);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top