Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an R function from Rcpp?

Tags:

r

rcpp

Here is a minimal example:

require(Rcpp)
require(inline)

src <- '
 Rcpp::Environment glob =  Rcpp::Environment::global_env();
 glob.assign( "foo" , "function(x) x + 1" );
'

myFun <- cxxfunction(body=src,plugin = "Rcpp")
myFun()

foo
[1] "function(x) x + 1"

Without surprise, what I get is a character variable and not a function.

like image 599
ed82 Avatar asked Oct 15 '25 16:10

ed82


1 Answers

You need the usual parse/eval combination to transform the string into an object.

foo <- eval( parse( text = "function(x) x+1") ) 
foo( 1:10 )
# [1]  2  3  4  5  6  7  8  9 10 11

In Rcpp, you can use an ExpressionVector.

// [[Rcpp::export]]
void fun(){
    ExpressionVector exp( "function(x) x+1" ) ;
    Function f = exp.eval();

    Rcpp::Environment glob =  Rcpp::Environment::global_env();
    glob.assign( "foo" , f );
}
like image 197
Romain Francois Avatar answered Oct 17 '25 05:10

Romain Francois