Alex Rivera | Logout

How to step through an R script from the beginning?

Asked 2011-09-20T13:59:08.117
40

I want to step through an R script. I saw the "debug" command while searching for how to do this but that seems to only apply to functions. This script doesn't have any functions.

The "browser" command looked promising so I put "browser()" as the first line of my script but it didn't seem to do anything when I ran it.

How do I get the script to pause on the first line so I can step through it?

Edit
Report

3 Answers

9

One popular way is to do this from your 'IDE' or editor -- Emacs / ESS do it very well, others do it too.

The basic idea is that you send either the line under the cursors, or function, or block, ... to the associated R process. Several other editors support this, including RStudio. My preference is still with ESS, but I am sure you can find something suitable.

Lastly, browser() et al can do that from within the R process but it is a little less pointy-clickety. Read the documentation, or books like Chambers "Software for Data Analysis" (Springer, 2008).

answered 2011-09-20T14:03:26.737
9

I'm partial to RStudio, so I recommend the following:

  1. Download RStudio
  2. Open your R Script
  3. put your cursor on the first line
  4. click ctrl + enter (PC/Linux) or command + return (Mac)
  5. repeat!

A nice feature of RStudio is that RStudio server can run great on a headless server. You then connect to the server via http in a web browser on your local machine. I use this configuration when running R on EC2 instances. RStudio maintains state so if I lose internet access on my train ride, when I get signal back RStudio picks up exactly where I left off and my remote machine has no idea that I disconnected and reconnected. Note that RStudio server is currently only supported on FC/CentOS and Debian/Ubuntu. Although it may compile under other variants of *nix.

answered 2011-09-20T14:14:23.543
6

For an R only solution, which evaluates complete expressions rather than individual lines, try this:

sourcep <- function(file){
  coms <- parse(file)
  for (i in seq_along(coms)){
    print(coms[[i]])
    eval(coms[[i]],envir=.GlobalEnv)
    mess <- paste("Expression",i,"of",length(coms),"parsed. Press <return> to continue.")
    cat(mess)
    readLines(n=1)
  }
}

You call this as you would call source (though this is much more basic and doesn't include any of its options). Basically, it uses parse to create a list of the parsed, but unevaluated expressions from your source file, then iterates through this list to print the expression, evaluate it in the global environment and then put a message to indicate the progess. The final line is the one that creates the pausing: a call to read a single line from stdin().

answered 2011-09-20T14:40:23.323

Your Answer