Re: [Rd] Creating functions programmatically

From: Gabriel Becker <gmbecker_at_ucdavis.edu>
Date: Wed, 03 Oct 2012 07:33:03 -0700

Hadley,

You could do this:

make_fun = function(args, body, env)
{
f = function()
formals(f) = args
body(f) = body
environment(f) = env
f
}

If for some reason using function() itself as Duncan suggested won't work.

Note: args will need to be the right kind of pairlist, eg what is returned from alist(a=, b=5), NOT alist(a, b=5) for this not to fail.

~G

On Wed, Oct 3, 2012 at 7:26 AM, Duncan Murdoch <murdoch.duncan_at_gmail.com>wrote:

> On 03/10/2012 10:16 AM, Hadley Wickham wrote:
>
>> Hi all,
>>
>> A function has three components: arguments, body and environment. Is
>> there no base function that allows us to create a function from those
>> three components?
>>
>
> 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).
>
> Duncan Murdoch
>
>
> The best I could come up with is:
>>
>> make_function <- function(args, body, env = parent.frame()) {
>> args <- as.pairlist(args)
>> stopifnot(is.language(body))
>> f <- eval(call("function", args, body))
>> environment(f) <- env
>> f
>> }
>> mquote <- function(...) as.list(substitute(list(...))[**-1])
>>
>> add <- make_function(mquote(a = 1, b = a), quote(a + b))
>> add(1)
>> add(1, 2)
>>
>> add2 <- make_function(mquote(a = 1, b = a), quote(a + b + d))
>> d <- 3
>> add2(1)
>>
>> Am I missing a built in way to do this? Also, is there a built in
>> equivalent to my mquote (= multiquote, for producing a named list of
>> quoted inputs)?
>>
>> Thanks!
>>
>> Hadley
>>
>>
> ______________________________**________________
> R-devel_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/**listinfo/r-devel<https://stat.ethz.ch/mailman/listinfo/r-devel>
>

-- 
Gabriel Becker
Graduate Student
Statistics Department
University of California, Davis

	[[alternative HTML version deleted]]

______________________________________________
R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Wed 03 Oct 2012 - 14:35:49 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 Wed 03 Oct 2012 - 15:10:46 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive