InspectorSands
InspectorSands

Reputation: 2929

Execute R code from readline() function

I would like the user to be able to input code and have it executed. I can think of a pretty inefficient solution:

code <- readline("Enter code > ")
write(code, "code.R")
source("code.R")

Is there a better way of achieving this?

Upvotes: 0

Views: 53

Answers (1)

akuiper
akuiper

Reputation: 214927

You can use textConnection, here is a demo:

code <- readline("Enter code > ")
Enter code > df <- data.frame(x = 1:3)

source(textConnection(code))

df
  x
1 1
2 2
3 3

Or use eval(parse(text = code)):

eval(parse(text = code))

df
  x
1 1
2 2
3 3

Upvotes: 1

Related Questions