Search code examples
rcpp

Have error in trying to use R function in Rcpp for the first time


Trying to compile a function in Rcpp that brings in a R package called read_excel.

Not sure what the error means but perhaps it cant find the function in the package?

cppFunction('IntegerVector readYear(CharacterVector filePath ) {

 IntegerVector Year(filePath.size());
 int n=filePath.size();

 Environment pkg = Environment::namespace_env("readxl");

 Function read_excel=pkg["read_excel"];

 for( int i =0 ; i<n; i++){


 Year[i] = read_excel(Named("path") = filePath[i],
          _["range"] = "B3:B3",
          _["col_names"] = false );
 }
 return Year;
}')

Error message:

file391220cd2e2.cpp: In function ‘Rcpp::IntegerVector readYear(Rcpp::CharacterVector)’:
file391220cd2e2.cpp:18:22: error: invalid conversion from ‘SEXP {aka SEXPREC*}’ to ‘Rcpp::traits::storage_type<13>::type {aka int}’ [-fpermissive]
  Year[i] = read_excel(Named("path") = filePath[i],
                      ^
make: *** [file391220cd2e2.o] Error 1
g++ -std=gnu++11 -I"/opt/R/3.6.0/lib/R/include" -DNDEBUG   -I"/home/rstudio-user/R/x86_64-pc-linux-gnu-library/3.6/Rcpp/include" -I"/tmp/RtmpbaxzNs/sourceCpp-x86_64-pc-linux-gnu-1.0.2" -I/usr/local/include  -fpic  -g -O2  -c file391220cd2e2.cpp -o file391220cd2e2.o
/opt/R/3.6.0/lib/R/etc/Makeconf:176: recipe for target 'file391220cd2e2.o' failed
Error in sourceCpp(code = code, env = env, rebuild = rebuild, cacheDir = cacheDir,  : 
  Error 1 occurred building shared library.

Solution

  • The error message means that it is not directly possible to convert the return type of an R function (SEXP) to the storage type of an IntegerVector (int). You can instruct Rcpp to do so using Rcpp::as<int>(...):

    Rcpp::cppFunction('IntegerVector readYear(CharacterVector filePath ) {
    
     int n = filePath.size();
     IntegerVector Year(n);
    
     Environment pkg = Environment::namespace_env("readxl");
    
     Function read_excel=pkg["read_excel"];
    
     for(int i =0; i<n; ++i){
       Year[i] = Rcpp::as<int>(read_excel(_("path") = filePath[i],
                                          _["range"] = "B3:B3",
                                          _["col_names"] = false ));
     }
     return Year;
    }')
    

    BTW, I hope there is a good reason for doing this in C++, since as it is the function will be slower than the equivalent R function, since calling R functions from C++ has its price.