From cberry at tajo.ucsd.edu  Mon Oct 23 05:59:15 2006
From: cberry at tajo.ucsd.edu (Charles C. Berry)
Date: Sun, 22 Oct 2006 20:59:15 -0700
Subject: [Rd] Changing function arguments
In-Reply-To: <67DCA285A2D7754280D3B8E88EB5480211DDA481@MSGBOSCLB2WIN.DMN1.FMR.COM>
References: <67DCA285A2D7754280D3B8E88EB5480211DDA481@MSGBOSCLB2WIN.DMN1.FMR.COM>
Message-ID: <Pine.LNX.4.64.0610222028190.21767@tajo.ucsd.edu>


See

 	?body
 	?parse
 	?deparse
 	?gsub

> foo <- function(x) x+.1
> bar <- function(y) y+foo(x=1) + foo(x=2)
> bar(1)
[1] 4.2
> body(bar)
y + foo(x = 1) + foo(x = 2)
> body(bar) <- parse(text=gsub("x[ ]*=[ ]*([0-9])","x = 1 + \\1",deparse(body(bar))))
> bar(1)
[1] 6.2
> body(bar)
y + foo(x = 1 + 1) + foo(x = 1 + 2)
>

There are many, many ways to skin this cat.

The 'parse( text = ... )' is but one.

Operating on parsed objects without deparsing them is often 
preferred.

On Sun, 22 Oct 2006, McGehee, Robert wrote:

> R-Developers,
> I'm looking for some help computing on the R language.
>
> I'm hoping to write a function that parses a language or expression
> object and returns another expression with all instances of certain
> argument of a given function altered. For instance, say I would like my
> function, myFun to take an expression and whenever the argument 'x'
> appears within the function FUN inside that expression, return an
> altered expression in which 'x' is incremented by one.
>
> Thus,
>> x <- expression(FUN(x = 0) + log(FUN(x = 3)))
>> myFun(x)
> [1] expression(FUN(x = 1) + log(FUN(x = 4)))
>
> Conceptually, it looks like I want to recursively break a language
> object into its component functions, search for FUN and increment one of
> its arguments ('x'), then reassemble and return the resulting
> expression. However, I haven't been able to come up with a clean way to
> do this. Suggestions would be greatly appreciated.
>
> Thanks in advance,
> Robert
>
> Robert McGehee
> Quantitative Analyst
> Geode Capital Management, LLC
> 53 State Street, 5th Floor | Boston, MA | 02109
> Tel: 617/392-8396    Fax:617/476-6389
> mailto:robert.mcgehee at geodecapital.com
>
>
>
> This e-mail, and any attachments hereto, are intended for us...{{dropped}}
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>

Charles C. Berry                        (858) 534-2098
                                          Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	         UC San Diego
http://biostat.ucsd.edu/~cberry/         La Jolla, San Diego 92093-0717




[Rd] Changing function arguments
Charles C. Berry