Question

If I have a character vector, how can I tell R to execute it as a command?

Simple example:

> a <- paste("2", "+", "3")

>a

>[1] "2 + 3"

I would like R to actually do 2+3, and not just print the content of "a".

Was it helpful?

Solution

The way to do it is

a <- paste("2", "+", "3")
eval(parse(text = a))

But, in general, it's not a great idea. There's usually a better way to do what you're trying to do.

> require(fortunes)
> fortune("parse")

If the answer is parse() you should usually rethink the question.
   -- Thomas Lumley
      R-help (February 2005)

There's lots of info on why eval(parse()) is considered a "bad practice" in the answers to What specifically are the dangers of eval(parse())?; in summary it is

  • bug-prone

  • harder to debug

  • usually there's a more readable way to do whatever you're trying to do

  • can pose a security risk

(though that last one probably doesn't apply for most R use cases)

OTHER TIPS

eval(parse(text=paste("2", "+", "3")))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top