1

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".

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
Gabriele
  • 13
  • 2
  • 1
    As the answers mention, there is a way to do this, but it is generally not the best way to accomplish what you want. If you tell us why you want to do this we may be able to point you to a better approach. – Greg Snow Mar 21 '14 at 16:28

2 Answers2

4

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)

Community
  • 1
  • 1
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • Interesting. Could you extend you anwser? Why is `parse` a bad idea? – Paulo E. Cardoso Mar 21 '14 at 16:28
  • Thank you very much! Indeed, you are right. I asked a friend of mine about that this morning, and after looking at my code he just scowled and rethought everything with two nested for loops. – Gabriele Mar 22 '14 at 17:44
1
eval(parse(text=paste("2", "+", "3")))
Davide Passaretti
  • 2,741
  • 1
  • 21
  • 32