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.

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, as document. I'd move the function assignment inside the C++ function though.
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) ;
} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.