Re: [Rd] Creating functions programmatically

From: Peter Meilstrup <>
Date: Wed, 03 Oct 2012 15:05:53 -0700

On Wed, Oct 3, 2012 at 7:47 AM, Hadley Wickham <> wrote:
>> There is: it is `function`. The parser converts your function definitions
>> into a call to it. (It has 3 arguments: the formals, the body, and the
>> srcref. The environment is added when it is evaluated.)
>> So your make_function below is pretty similar (but because `function` is
>> primitive, some of the evaluation rules might be different).
> Hmm, I thought I had it working, but now I can't figure out the
> arguments to `function`:
>> `function`(NULL,NULL)
> function ()
>> `function`(alist(a = 1), NULL)
> Error: invalid formal argument list for "function"
> I'm obviously missing something dumb.

I think `function` does not eval its arguments, and it demands a pairlist. So this works:

f <- eval(substitute(`function`(args, body), list(args=as.pairlist(alist(a=1)), body=quote(a+1))))

The other thing to notice is a syntax difference between function and ordinary calls: when writing

function(b=default, a) {}

"a" is interpreted as a name rather than value; to programatically get the same effect you'd have to use

alist(b=default, a= )

Peter mailing list Received on Wed 03 Oct 2012 - 22:10:22 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 04 Oct 2012 - 02:40:45 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive