From ggrothendieck at gmail.com  Tue Dec 19 00:55:48 2006
From: ggrothendieck at gmail.com (Gabor Grothendieck)
Date: Mon, 18 Dec 2006 18:55:48 -0500
Subject: [Rd] turning expression object to function
In-Reply-To: <b0808fdc0612181006t5316da91pe6192333c03b2c94@mail.gmail.com>
References: <b0808fdc0612181006t5316da91pe6192333c03b2c94@mail.gmail.com>
Message-ID: <971536df0612181555w2cba1cddvd48d4c5579313802@mail.gmail.com>

Here is one possibility.  It does not use the second argument in your function
call but instead assumes the arguments of the output function are
those variables
in the expression that have not been assigned in the list L in the
order encountered.

library(gsubfn)
asFun <- function(e, L = NULL, env = parent.frame()) {
  fo <- ~ x
  fo[[2]] <- e[[1]]
  fun <- fn$force(as.formula(do.call(substitute, list(fo, L))))
  environment(fun) <- env
  fun
}

asFun(expression(a+b+c), list(b = 1, c = 2)) # function (a) a + 1 + 2




On 12/18/06, Antonio, Fabio Di Narzo <antonio.fabio at gmail.com> wrote:
> Dear all,
> I have the following problem.
>
> Given an expression object 'expr' containing a certain set of symbols
> (say 'a', 'b', 'c'), I would like to translate the expression object
> in an R function of, say, 'a', programmatically. Here an example of
> what I mean.
>
> Given:
> > expr <- expression(a+b+c)
>
> a call like:
> > asFunctionOf(expr, 'a', list(b=1, c=2))
>
> should return a function (not necessarly formally) equivalent to
> > function(a) a+1+2
>
> Some suggestions?
>
> Best regards,
> Antonio.
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>



[Rd] turning expression object to function
Gabor Grothendieck