2

How can I call an R function that does not belong to any R package into a C++ code?. I can show you what I mean through a very semplicistic example. Suppose I have an R file where I write

myRfunction <- function(x){
 return(x+2)
}

and I want to use it in a generic c++ code. So, I write something like

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
using namespace std;

// [[Rcpp::export]]

arma::vec myCppfunction(arma::vec y){
 arma::sec results = myRfunction(y);  /* Or whatever I have to do to call it! */
 return results;
}

Can someone tell me how to do it? What is the general procedure? Thank you all.

  • Other duplicates: https://stackoverflow.com/questions/29463754/calling-r-function-from-rcpp and https://stackoverflow.com/questions/38016851/call-r-functions-in-rcpp – coatless Nov 14 '17 at 15:32

2 Answers2

3

Example. In R:

> timesTwoR <- function(x) 2*x

The cpp file:

#include <Rcpp.h>
using namespace Rcpp;

Function timesTwoFromR = Environment::global_env()["timesTwoR"];

// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
  return timesTwoFromR(x);
}

Then, in R:

> timesTwo(42)
[1] 84
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
1

Alternatively, you can pass the R function as an argument to the C++ function, something like this:

// [[Rcpp::export]]
NumericVector call_r_fun(NumericVector x, Function f) {
  return f(x) ;
} 
Romain Francois
  • 17,432
  • 3
  • 51
  • 77