Remi.b
Remi.b

Reputation: 18229

Is there a way to run a code which is contained in a string object (in R)?

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?

Upvotes: 4

Views: 87

Answers (2)

James
James

Reputation: 66844

You can source from a textConnection:

source(textConnection(to_run))
alpha
  a b
1 1 2
2 2 3
3 3 4

Upvotes: 6

Hong Ooi
Hong Ooi

Reputation: 57696

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.

Upvotes: 4

Related Questions