Re: [R] functions and strings

From: Robin Hankin <r.hankin_at_noc.soton.ac.uk>
Date: Wed 13 Sep 2006 - 10:51:02 GMT

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

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Wed Sep 13 21:58:05 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Wed 13 Sep 2006 - 16:30:17 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.