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

Consider the following line:

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 to run code written as a string character in an object to_run?

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

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 any other, more direct solution?

+4
source share
2 answers

You can sourcefrom textConnection:

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

eval(parse(text=to_run))- standard idiom. You should carefully consider whether you really want to do this. Evaluating free text is a great way to inject holes into your system.

+4
source

All Articles