Running an R script line-by-line

I just found out how to run a R script from the R Console under Windows.

source("arrrFile.R")

The problem is, this command runs “silently”.
How can I run the file command-by-command as I would type it in the console?

Answer

You can use R’s built-in debugger; it must be triggered on a function, so a little wrapper is needed:

sourceDebugging<-function(f){
 #Function to inject the code to
 theCode<-function(){}
 #Injection
 parse(text=c('{',readLines(f),'}'))->body(theCode)
 #Triggering debug
 debug(theCode)
 #Lift-off
 theCode()
}
sourceDebugging(<file with code>)

This is quite handy for debug (gives you a chance to inspect the state after each line), however, will only evaluate in a fresh environment of theCode instead of source‘s default .GlobalEnv… this means for instance that the variables made inside will disappear unless explicitly globalised.

Option two is just to emulate writing from keyboard and pressing ENTER… but as caracal pointed out this can be achieved just by source(<file with code>,echo=TRUE).

Attribution
Source : Link , Question Author : Fabian , Answer Author : Community

Leave a Comment