The Art of R Programming

(WallPaper) #1
You can arrange to automatically enter the debugger by writing
this code:

> options(error=recover)

Note, though, that if you do choose this automatic route, it will whisk
you into the debugger, even if you simply have a syntax error (not a useful
time to enter the debugger).
To turn off any of this behavior, type the following:

> options(error=NULL)

You’ll see a demonstration of this approach in the next section.

13.3.6 Extended Example: Two Full Debugging Sessions..................


Now that we’ve looked at R’s debugging tools, let’s try using them to find
and fix code problems. We’ll begin with a simple example and then move
on to a more complicated one.

13.3.6.1 Debugging Finding Runs of Ones
First recall our extended example of finding runs of 1s in Chapter 2. Here is
a buggy version of the code:

1 findruns <- function(x,k) {
2 n <- length(x)
3 runs <- NULL
4 for (i in 1:(n-k)) {
5 if (all(x[i:i+k-1]==1)) runs <- c(runs,i)
6 }
7 return(runs)
8 }

Let’s try it on a small test case:

> source("findruns.R")
> findruns(c(1,0,0,1,1,0,1,1,1),2)
[1]3467

The function was supposed to report runs at indices 4, 7, and 8, but it
found some indices that it shouldn’t have and missed some as well. Some-
thing is wrong. Let’s enter the debugger and take a look around.

> debug(findruns)
> findruns(c(1,0,0,1,1,0,1,1,1),2)
debugging in: findruns(c(1, 0, 0, 1, 1, 0, 1, 1, 1), 2)
debug at findruns.R#1: {

292 Chapter 13

Free download pdf