Parse multi-line expressions in the R / Emulating R console

I would like to have an R function that allows me to emulate the R console with the difference that expressions are evaluated in a different environment than the global environment. (I want to use it for an alternative debugging method in R, which allows you to restore the local parameters with which the function was called, and then debug it by simply inserting the function code into the emulated R console step by step). Here is a function that uses parse and eval and does the job halfway (the emulated console stops when you press Escape):

my.console = function() { while(TRUE) { tryCatch({ expr.out <- capture.output(eval(parse(prompt=": "))) if (length(expr.out)>0) { cat(expr.out,"\n") } }, error = function(e) { str = as.character(e) message(str) }) } } console.env = new.env(parent=globalenv()) console.env$hello = "Hello World" environment(my.console) <- console.env my.console() 

Then you can evaluate simple expressions in an emulated console, for example

 : 5*5 [1] 25 : hello [1] "Hello World" 

The problem is that I cannot parse multiline code, for example. when inserting the start of an if statement from my script, an error will be displayed.

 : if (TRUE) { Error in parse(prompt = ": "): 2:0: unexpected end of input 

The R console understands that the next line will execute more code and change the prompt to +. I wonder if there is also a variant of a parsing function that has similar behavior. So far, my only idea would be a very dirty approach to finding the substring "unexpected end of input" in the error message, and if further parsing is found. But, for example, since some R error messages seem to depend on the language R is running in, I'm not very happy with this approach. Does anyone know how I could write a better emulated R console that can parse multi-line R code?

+4
source share
2 answers

Why not try separating code and parse commands, for example,

 s <- scan(what="list", multi.line=TRUE) for(i in 1:length(s)){ capture.output(eval(parse(text=s)[i])) # etc... } 
+1
source

If you want to interactively go step-by-step through your code, you can use the built-in browser() function with the n command, see ?browser . Usage example:

 f <- function(x) { # invoke interactive debugging browser() # rest of the function - by pressing 'n' while in browser mode, the expressions # will be executed one after another and you are able to explore the # intermediate values of variables etc. (as in standard R promt) y <- x^2 [...] } 

If this does not meet your needs, you can look at the source code of the browser .

0
source

All Articles