Browse[1]> i
[1] 2
Browse[1]> x[i:(i+k-1)]
[1]00
That’s right, too. We could go another iteration, but instead, let’s look
at the last iteration, a place where bugs frequently arise in loops. So, let’s
add a conditional breakpoint, as follows:
findruns <- function(x,k) {
n <- length(x)
runs <- NULL
for (i in 1:(n-k)) {
if (all(x[i:(i+k-1)]==1)) runs <- c(runs,i)
if (i == n-k) browser() # break in last iteration of loop
}
return(runs)
}
And now run it again.
> source("findruns.R")
> findruns(c(1,0,0,1,1,0,1,1,1),2)
Called from: findruns(c(1, 0, 0, 1, 1, 0, 1, 1, 1), 2)
Browse[1]> i
[1] 7
This shows the last iteration was fori=7. But the vector is nine ele-
ments long, andk=2, so our last iteration should bei=8. Some thought
then reveals that the range in the loop should have been written as follows:
for (i in 1:(n-k+1)) {
By the way, note that the breakpoint that we set usingsetBreakpoint()
is no longer valid, now that we’ve replaced the old version of the object
findruns.
Subsequent testing (not shown here) indicates the code now works.
Let’s move on to a more complex example.
13.3.6.2 Debugging Finding City Pairs
Recall our code in Section 3.4.2, which found the pair of cities with the clos-
est distance between them. Here is a buggy version of that code:
1 returns the minimum value of d[i,j], i != j, and the row/col attaining
2 that minimum, for square symmetric matrix d; no special policy on
3 ties;
4 motivated by distance matrices
Debugging 295