[R] functions and strings

Robin Hankin r.hankin at noc.soton.ac.uk
Wed Sep 13 12:51:02 CEST 2006


Rich

that is sweeeeeeeeeeeeet

and does exactly what I want.

Thank you very much.


best wishes

rksh

On 13 Sep 2006, at 10:54, Rich FitzJohn wrote:

> Hi,
>
> Perhaps try this (based on 'bquote'):
>
> rewrite.expression <- function(expr, to, dep) {
>   f <- function(expr) {
>     if ( length(expr) == 1 )
>       if ( expr == as.name(dep) )
>         as.name(to)
>       else
>         expr
>     else
>       as.call(lapply(expr, f))
>   }
>   f(expr)
> }
>
> rewrite <- function(expr, to, dep='x') {
>   rewrite.expression(substitute(expr), to, dep)
> }
>
>> rewrite(1 + sin(cos(x)) + exp(x^2), 'xyz')
> 1 + sin(cos(xyz)) + exp(xyz^2)
>> rewrite(sin(x)+exp(x), 'xyz')
> sin(xyz) + exp(xyz)
>> rewrite(sin(i) + cos(sin(i^2)), 'tti', 'i')
> sin(tti) + cos(sin(tti^2))
> ## Or, closer to your example, using the name of the argument and body
> ## of the function:
> f <- function(r)
>   2*r/sin(r) - b
>
>> rewrite.expression(body(f), 'foo', names(formals(f)))
> 2 * foo/sin(foo) - b
>
> Hope that helps,
> Rich
>

--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743



More information about the R-help mailing list