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

Viewed 64

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?

2 Answers
Related