Skip to content

Running R scripts with interactive-style evaluation

5 messages · Duncan Murdoch, Marc Aurel Kiefer, William Dunlap +1 more

#
Hi,

when running a R-script like this:

enable_magic()
compute_stuff()
disable_magic()

the whole script is parsed into a single expression and then evaluated, whereas when using the interactive shell after each line entered, a REPL loop happens.

Is there a way to make a script evaluation behave like this, because I need a single REPL iteration for every expression in the script.

It doesn't matter if it's a source()-like way or "R CMD BATCH" or even feeding stdin to R or whatever...

Regards,

Marc
#
On 13-02-26 5:07 AM, Marc Aurel Kiefer wrote:
It's actually a vector of expressions that are evaluated one at a time, 
but close enough...
You don't say why you need that.  From your subject line, I'm guessing 
you want to do something like a user prompt, then wait for user input, 
then another user prompt, etc.? So the fact that disable_magic() was 
parsed at the beginning shouldn't matter.  Or does it?
I think it all depends on what kind of input users are allowed to type, 
but basically this is something you'll need to write yourself, I don't 
think any of the normal running modes of R will suit you.  Take a look 
at the source to source() or to the Sweave-related functions for ideas.

Duncan Murdoch
#
Thanks for your insights.

What I'm actually doing is the following:

I modified R in a way that the REPL loop always parses the input into an SEXPR, but depending on if "magic is enabled" or not, let R compute it or compute it via my own "backend".
As I wanted to keep the changes to R itself as minimally invasive as possible, there is a simple if-statement at the beginning of the REPL iteration which decides how to compute the expression.
using the R commands "enable/disable_magic()" one can change the behavior as required. This works fine when typing R code interactively, but not with a script, since it is only a single REPL iteration.
So I was looking for a way to get "interactive behavior" with scripts, without requiring too many changes to R itself.

Regards,

Marc
#
Which part of the read-eval-print loop loop ("REPL loop") do you need?

source(file, print=TRUE) gives you the printing part, which is what I usually want.

Opening a file connection and repeatedly calling parse(n=1) gives you the read part,
  > tf <- tempfile()
  > cat(file=tf, sep="\n", "x <- 1 +", "10 ; y <- 2:7", "10:3")
  > f <- file(tf, open="rt")
  > parse(f, n=1)
  expression(x <- 1 + 10)
  > parse(f, n=1)
  expression(y <- 2:7)
  > parse(f, n=1)
  expression(10:3)
  > parse(f, n=1)
  expression()
  > close(f)
and you can copy the code from source() to get the eval and print stuff right.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com