From h.wickham at gmail.com  Wed Oct  3 16:16:48 2012
From: h.wickham at gmail.com (Hadley Wickham)
Date: Wed, 3 Oct 2012 09:16:48 -0500
Subject: [Rd] Creating functions programmatically
Message-ID: <CABdHhvH9Q3L16aCQPg=Tn5N+GqJTDW2vhf3=y6_DYcUOXwYvmQ@mail.gmail.com>

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?

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

-- 
RStudio / Rice University
http://had.co.nz/



[Rd] Creating functions programmatically
Hadley Wickham