Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

class

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?

like image 479
Remi.b Avatar asked Dec 26 '22 16:12

Remi.b


2 Answers

You can source from a textConnection:

source(textConnection(to_run))
alpha
  a b
1 1 2
2 2 3
3 3 4
like image 95
James Avatar answered Dec 28 '22 07:12

James


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.

like image 41
Hong Ooi Avatar answered Dec 28 '22 07:12

Hong Ooi