From marc_schwartz at comcast.net  Mon Dec 18 21:24:39 2006
From: marc_schwartz at comcast.net (Marc Schwartz)
Date: Mon, 18 Dec 2006 14:24:39 -0600
Subject: [Rd] turning expression object to function
In-Reply-To: <b0808fdc0612181006t5316da91pe6192333c03b2c94@mail.gmail.com>
References: <b0808fdc0612181006t5316da91pe6192333c03b2c94@mail.gmail.com>
Message-ID: <1166473479.4771.36.camel@localhost.localdomain>

On Mon, 2006-12-18 at 19:06 +0100, Antonio, Fabio Di Narzo 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.

Let me offer some pointers and a couple of possible examples:

?call
?as.function
?alist
?eval
?parse


expr <- expression(a + b + c)

> as.function(alist(a = , b = 1, c = 2, eval(expr)))(5)
[1] 8

> as.function(alist(a = , b = 1, c = 2, eval(expr)))(5, 10, 8)
[1] 23



MyExpr <- paste(letters[1:3], collapse = " + ")

> MyExpr
[1] "a + b + c"

> as.function(alist(a = , b = 1, c = 2, eval(parse(text = MyExpr))))(6)
[1] 9


HTH,

Marc Schwartz



[Rd] turning expression object to function
Marc Schwartz