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?
You can source
from a textConnection
:
source(textConnection(to_run))
alpha
a b
1 1 2
2 2 3
3 3 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With