[R] Can I execute the content of a character vector?

Gabor Grothendieck ggrothendieck at gmail.com
Mon Nov 13 19:54:56 CET 2006


On 11/13/06, Roger Bivand <Roger.Bivand at nhh.no> wrote:
> On Mon, 13 Nov 2006, Luiz Rodrigo Tozzi wrote:
>
> > Hi
> >
> > I want to know if there is any possibility of "executing" the content of a
> > vector, for example:
> >
> > example=c("Test",1,0,0,0,"seq(14,42,by=2)",0,0,1)
> >
> > i want to know if there is anything like "execute(example[6])"
>
> You can say:
>
> eval(parse(text=example[6]))
>
> but it is difficult to avoid shooting people in the feet with it, unless
> that is what you want ...
>
> eval(parse(text=example[1]))


We could enclose strings to be evaluated in backticks:

example <- c("Test",1,0,0,0,"`seq(14,42,by=2)`",0,0,1)

pat <- "^`(.*)`$"
f <- function(x)  # strip backticks in 1st and last posn and evaluate
   if (regexpr(pat, x) > 0)
      eval.parent(parse(text = sub(pat, "\\1", x)))
   else x

example <- c("Test",1,0,0,0,"`seq(14,42,by=2)`",0,0,1)
lapply(example, f)

>
>
> >
> > i really need this because this object example is created from a parameter
> > file with names, flags and this "seq" somethimes will be something like
> > c("1","99,"3") or even c("")
> >
> > executing the content would be an easier step for me
> >
> > thanks!
> >
> >
>
> --
> Roger Bivand
> Economic Geography Section, Department of Economics, Norwegian School of
> Economics and Business Administration, Helleveien 30, N-5045 Bergen,
> Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
> e-mail: Roger.Bivand at nhh.no
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list