From hadley at rice.edu  Thu May 26 18:08:40 2011
From: hadley at rice.edu (Hadley Wickham)
Date: Thu, 26 May 2011 11:08:40 -0500
Subject: [Rd] Is it possible to define a function's arguments via a
 wildcard in 'substitute()'?
In-Reply-To: <4DDE6E97.1040900@googlemail.com>
References: <4DDE6E97.1040900@googlemail.com>
Message-ID: <BANLkTinTmxc9S6HcDfff+TKF7fz9k3MkRg@mail.gmail.com>

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/



[Rd] Is it possible to define a function's arguments via a wildcard in 'substitute()'?
Hadley Wickham