Re: [R] functions and strings

From: Peter Dalgaard <p.dalgaard_at_biostat.ku.dk>
Date: Wed 13 Sep 2006 - 11:44:39 GMT

Robin Hankin <r.hankin@noc.soton.ac.uk> writes:

> Rich
>
> that is sweeeeeeeeeeeeet
>
> and does exactly what I want.
>
> Thank you very much.

I just wonder whatever substitute() did to get ignored like that?

> substitute(1 + sin(cos(x)) + exp(x^2), list(x=quote(xyz)))
1 + sin(cos(xyz)) + exp(xyz^2)  

>
> 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.
>

-- 
   O__  ---- Peter Dalgaard             ุster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)                  FAX: (+45) 35327907

______________________________________________
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 Thu Sep 14 01:48:06 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.