Search code examples
rpackagercpp

In a package, how to call a R function from this package with Rcpp?


The Rcpp quick reference guide shows how to call a R function from a package in a Rcpp code. It takes as example the stats package. But if I do a package and I want to call a R function from this package with Rcpp, also in this package, how should I do? I didn't try, but I guess that following the stats example, simply replacing stats with mypackage, will not work because mypackage does not exist yet during the compilation. I hope my English phrasing is clear...


Solution

  • I set up a quick package tstpkg via a call to kitten.r using the pkgKitten package.

    I added this R function:

    theAnswer <- function() { 42L }
    

    and indeed we can call it from the same package simply by not prefixing any namespace etc as in

    #include <Rcpp/Light>
    
    // [[Rcpp::export]]
    bool checkAnswer() {
        Rcpp::Function f("theAnswer");
        int val = Rcpp::as<int>(f());
        return val == 42;
    }
    

    A quick ad-hoc call on the command-line confirms:

    $ Rscript -e 'library(tstpkg); theAnswer(); checkAnswer()'
    [1] 42
    [1] TRUE
    $