[R] How can I run a function to a piece of text?

Sundar Dorai-Raj sdorairaj at gmail.com
Fri Oct 16 20:46:15 CEST 2009


Based solely on what you told us, this can be done using eval(parse(text=...))

cmd <- sprintf("mean(%s)", script)
eval(parse(text = cmd))

However, with more context, there may be a better solution. See, for example,

install.packages("fortunes")
library(fortunes)
fortune("parse()")

HTH,

--sundar

On Fri, Oct 16, 2009 at 11:39 AM, Javier PB
<j.perez-barberia at macaulay.ac.uk> wrote:
>
> Dear users,
>
> I got really stuck trying to apply a function to a piece of code that I
> created using different string functions.
>
> To make things really easy, this is a wee example:
>
> x<-c(1:10)
> script<-"x, trim = 0, na.rm = FALSE"        ##script created by a number of
> paste() and rep() steps
> mean(script)                                       ##function that I want to
> apply: doesn't work
>
> Is there any way to convert the "script" class so that the function mean()
> can read it as if it were text typed in the console?
>
> Thanks and have a superb day
>
> Javier
>
>
>
> --
> View this message in context: http://www.nabble.com/How-can-I-run-a-function-to-a-piece-of-text--tp25930315p25930315.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org 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.
>




More information about the R-help mailing list