Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

from an expression to a language object

Tags:

r

I would like to use microbenchmark::microbenchmark(), but with arguments in the ... that I programatically construct, with strings.

Example :

# classic way
microbenchmark(head(1:1e6), head(1:1e8), times = 10) # (interesting...)
# define my arguments
functionStrings <- lapply(c(6,8), function(ni) paste0("head(1:1e", ni, ")"))
# will not work
do.call(microbenchmark, lapply(functionStrings, function(vi) parse(text=vi)))

The problem here is that microbenchmark works with unevaluated expressions, of class "language", that it then deparse(). Doing deparse() on a normal expression unfortunately deparse the expression object...

bla <- quote(head(1:1e6))
blou <- parse(text = "head(1:1e6)")
eval(bla) ; eval(blou) # Same thing, but....
deparse(bla)
deparse(parse(text = "head(1:1e6)"))

How to get from a string or an expression (argument or output of parse() above) to a language object (output of quote() above) ?

like image 567
Antoine Lizée Avatar asked Dec 11 '25 06:12

Antoine Lizée


1 Answers

The anonymous function in the last line of the first block of code should be:

function(vi) parse(text=vi)[[1]]

That is:

  • the argument to parse is named text and not test and
  • a call object is needed rather than an expression so use [[1]] .
like image 181
G. Grothendieck Avatar answered Dec 14 '25 02:12

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!