[R] functions and strings
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Wed Sep 13 13:44:39 CEST 2006
Robin Hankin <r.hankin at 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 at 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 at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list