Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate expressions in environments in Rcpp

Tags:

r

rcpp

I am looking at if it is possible to have the same functionality as with() in R in Rcpp for environments.

For example, in R I could create an environment, add two variables and use with() to evaluate an expression using only the variablenames:

e <- new.env()
e$x <- 1
e$y <- 2

with(e,
     x + y
     )

I could do something similar in Rcpp, but it requires indexing of the environment:

f <- cxxfunction(signature(env="environment"), '
Environment e(env);
double Res = (double)e["x"] + (double)e["y"];
return(wrap( Res ));

', plugin = "Rcpp" )

f(e)

Is it possible to evaluate an expression using only the variable names in Rcpp? The reason I am asking is because I want to write a sort of dynamic C++ function where you can add expressions. For example with some dummy code that doesn't work:

f <- cxxfunction(signature(env="environment"), sprintf('
Environment e(env);
double Res;
// Res = with(e, %s );
return(wrap( Res ));
','x + y'), plugin = "Rcpp" )
like image 903
Sacha Epskamp Avatar asked May 02 '12 07:05

Sacha Epskamp


1 Answers

I don't think you can: at compile-time, your variables are unknown. You do have to resort to dynamic lookups which is what R does. In essence, you'd need to recreate a parser for your x + y expression.

like image 187
Dirk Eddelbuettel Avatar answered Sep 30 '22 11:09

Dirk Eddelbuettel