0
votes

I was trying to expose my C++ class through Rcpp by building a package. It seems that module is not allowed in RStudio auto-generated template. For example, if we compare the NAMESPACE file generated by Rcpp.package.skeleton(myPackage, module=TRUE) and by RStudio, importFrom(Rcpp, loadModule) is not in the RStudio NAMESPACE file. Did I miss something? How can I enable RStudio to generate module allowed package template?

Here is a minimal example to show my C++ codes in case someone would like to try it in RStudio

class Student{
private:
  double age;
  double GPA;
public:
  Student(double age_, double GPA_):age(age_),GPA(GPA_){}

  double sum(double x, double myGPA){
    GPA = myGPA;
    return GPA + x;
  }
  double times(double x, double myage){
    age = myage;
    return age*GPA*x;
  }
};


RCPP_MODULE(my_module){
  class_<Student>("Student")
  .constructor<double, double>()
  .method("sum", &Student::sum)
  .method("times",&Student::times);
}
2

2 Answers

3
votes

In very, very short: No. Or maybe "sort of; not completely".

A bit more expanded: The auto-package stub creates a working basic Rcpp package. But eg not an RcppArmadillo package (and this has bitten people before).

And we do include a complete example for Rcpp Modules in the package in this directory (which is used by the unit tests) so you may have to do a few steps by hand if you go that route.

You can also try the helper function Rcpp.package.skeleton() with the option module=TRUE which the other formal option.

So in sum you cannot reasonably expect the RStudio GUI to support every available permutation.

3
votes

Simply put, RStudio is limited in generating Rcpp project types for this version (1.0). Per a PR, custom package templates are incoming!

To get around this limitation, try the following:

  1. Close all open projects.
  2. Run the following: Rcpp.package.skeleton("myPackage", module=TRUE)
  3. New Project -> From Existing Directory or use devtools::use_rstudio() to generate the .Rproj.

Edit 1

Per the comment, what really is happening is two fold:

First, the module definition needs to be updated to be:

#include <Rcpp.h>

class Student{
private:
    double age;
    double GPA;
public:
    Student(double age_, double GPA_):age(age_),GPA(GPA_){}

    double sum(double x, double myGPA){
        GPA = myGPA;
        return GPA + x;
    }
    double times(double x, double myage){
        age = myage;
        return age*GPA*x;
    }
};


RCPP_MODULE(my_module){
    using namespace Rcpp ; // Added (if not done globally)

    class_<Student>("Student")
    .constructor<double, double>()
    .method("sum", &Student::sum, "Sum")      // Add some documentation (optional)
    .method("times",&Student::times, "Times");
}

Next, in some R code file add:

loadModule("my_module", TRUE)

Build and Reload

Then, you have:

s <- new( Student, 1, 2 )
s$sum(2,4)
# [1] 6
s$times(5,6)
# [1] 120