I'd like to replicate the following R function in C/C++:
fn1 = function(a, b) eval(a, b)
fn1(substitute(a*2), list(a = 1))
#[1] 2
My first couple of attempts result in an error (and sometimes in a crash), probably because I'm not getting the environment from a list object (I looked at the R source code, and it was using a bunch of internal functions at this point which I don't think I can use), and I think that's what Rf_eval
wants and not the object itself.
require(Rcpp)
require(inline)
fn2 = cxxfunction(signature(x = "SEXP", y = "SEXP"),
'return Rf_eval(x, y);')
fn2(substitute(a*2), list(a = 1))
# error, object 'a' not found
Another attempt was trying to call base R eval
instead, which also gave the same error:
require(Rcpp)
require(inline)
fn3 = cxxfunction(signature(x = "SEXP", y = "SEXP"),
'Function base_eval("eval"); return base_eval(x, y);',
plugin = 'Rcpp')
fn3(substitute(a*2), list(a = 1))
# again, object 'a' not found
What's missing in each approach and how can I make both of them work?