4

Consider the following string:

to_run = "alpha = data.frame(a=1:3, b=2:4)"

or

to_run = "for (i in 1:10){print(i);print('Hello World!')}"

How can one run the code which is written as a string character in the object to_run?

One solution is to output the object on an external file and to source it:

write.table(to_run, 'I.am.a.Path/folder/file.name', quote=F, row.names=F, col.names=F)
source('I.am.a.Path/folder/file.name')

Is there another, more straightforward solution?

durron597
  • 31,968
  • 17
  • 99
  • 158
Remi.b
  • 17,389
  • 28
  • 87
  • 168

2 Answers2

6

You can source from a textConnection:

source(textConnection(to_run))
alpha
  a b
1 1 2
2 2 3
3 3 4
James
  • 65,548
  • 14
  • 155
  • 193
4

eval(parse(text=to_run)) is the standard idiom. You should consider carefully whether you really want to do this though. Evaluating arbitrary text is a great way to introduce security holes into your system.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
  • +1 But you probably should warn more strongly against the evil that is `eval(parse())`. – Roland Dec 19 '13 at 09:36
  • @Hong Ooi Thanks a lot! I don't quite understand though why is it such a security issue. Could you give some words about it? My programs won't run on internet. I know nothing about networks! They run on my personal machine or on a cluster with the aim to gain insights in the field of biology or statistics. I don't think I really have to be scared for security issues when using such codes, is it correct? – Remi.b Dec 19 '13 at 10:01
  • 1
    @Remi.b The real issue is not security. R doesn't claim to be secure that way anyway. However, code that does things like this is usually badly written and hard to maintain. There is almost always a better alternative available. – Roland Dec 19 '13 at 10:05
  • Ok, I start to grab the idea. I don't want to extend discussion here so I asked [this other question](http://stackoverflow.com/questions/20678930/why-is-it-a-bad-habit-to-parse-and-evaluate-a-string-code-in-r) concerning why it is a bad habit. Thanks a lot for your answers! – Remi.b Dec 19 '13 at 10:20