Is it possible to define a function's arguments via a wildcard in 'substitute()'?
I think for the case where you want to built up a call from a function
name + list of arguments, it's best to use call or as.call:
call("f", a = 1, b = 2, c = 3)
or if you already have the list:
l <- list(as.name("f"), a = 1, b = 2, c = 3)
as.call(l)
Hadley
On Thu, May 26, 2011 at 10:15 AM, Janko Thyson
<janko.thyson.rstuff at googlemail.com> wrote:
Dear List,
just out of pure curiosity: is it possible to define a function via
'substitute()' such that the function's formal arguments are specified by a
"wildcard" that is substituted when the expression is evaluated?
Simple example:
x.args <- formals("data.frame")
x.body <- expression(
? ?out <- myArg + 100,
? ?return(out)
)
expr <- substitute(
? ?myFoo <- function(
? ? ? ?ARGS,
? ? ? ?myArg
? ?){
? ? ? ?print("hello world!")
? ? ? ?print(ARGS)
? ? ? ?eval(BODY)
? ?},
? ?list(ARGS=x.args, BODY=x.body)
)
eval(expr)
myFoo(myArg=5)
# works
myFoo(a=1:3, stringsAsFactors=FALSE, myArg=5)
# does not work
It works for wildcard 'BODY' in the function's body, but not for wildcard
'ARGS' in the argument definition part of the function definition.
I thought that when writing a function that depends on some other function
like 'data.frame()', it would maybe be possible not to 'hardcode' the formal
arguments of 'data.frame()' in the new function def but to have it mapped
somewhat dynamically so that when 'data.frame()' changes, the new function
would change as well. This is probably a bad idea for countless reasons,
nevertheless I'd be interested in learning if it's possible at all ;-)
TIA,
Janko
______________________________________________ R-devel at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-devel
Assistant Professor / Dobelman Family Junior Chair Department of Statistics / Rice University http://had.co.nz/