[R] from character string to function body?
Atte Tenkanen
attenka at utu.fi
Sat Jul 7 21:42:26 CEST 2007
Thanks Sundar!
I wonder that - when evaluating F1 - the right mathematical formula is now also printed!
> F1
function (x)
x^3 + x^2 - 1
Atte
>
>
> Atte Tenkanen said the following on 7/7/2007 8:41 AM:
> > Dear R users,
> >
> > I wonder if it is possible to form a function from a character
> string. Here is an example:
> >
> >
> >> x=3
> >> `-`(`+`(`^`(x,3),`^`(x,2)),1) # Here is my function evaluated.
> > [1] 35
> >
> >> V=list("`-
> `","(","`+`","(","`^`","(","x",",",3,")",",","`^`","(","x",",",2,")",")",",",1,")") # Here I construct the string, it could be vector as well?
> >>
> >> S=noquote(paste(V,collapse=""))
> >>
> >> S
> > [1] `-`(`+`(`^`(x,3),`^`(x,2)),1) # Here is the same as a
> character string.
> >
> > Now I'd like to create a function using this string, something
> like this, but of course, this doesn't work:
> >
> > S=as.expression(S)
> >
> > F1<-function(x){S}
> >
> > Is there some way to do this?
> >
> > Cheers,
> >
> > Atte Tenkanen
> > University of Turku, Finland
> >
> > ______________________________________________
> > 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.
>
> How about:
>
> V <-
> list("`-
> `","(","`+`","(","`^`","(","x",",",3,")",",","`^`","(","x",",",2,")",")",",",1,")")
> # Here I construct the string, it could be vector as well?
> S <- paste(V, collapse = "")
>
> F1 <- function(x) {}
> body(F1) <- parse(text = S)
> F1(3)
> # [1] 35
> F1(2)
> # [1] 11
>
> HTH,
>
> --sundar
>
>
More information about the R-help
mailing list