I came across the function below in the Parlist section of the Expressions chapter in Advanced R:
make_function <- function(args, body, env = parent.frame()) {
args <- as.pairlist(args)
eval(call("function", args, body), env)
}
The function allows the user to construct a function from its component pieces: a list of formal arguments, a body, and an environment. E.g.
add <- make_function(alist(a = 1, b = 2), quote(a + b))
add
function (a = 1, b = 2)
a + b
class(add)
[1] "function"
I was wondering if the function could be modified so as to allow the user to input a string for the body argument? I have tried parse(text = 'a + b') but this returns an expression rather than a call as in quote(a + b):
class(quote(a + b))
[1] "call"
class(parse(text = 'x^m'))
[1] "expression"
Is there a way to construct a call object from a string?