Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
$
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading