The Art of R Programming

(WallPaper) #1
Sincekis 2—that is, we are checking for runs of length 2— theif()
statement should be checking the first two elements ofx, which are (1,0).
Let’s confirm:

Browse[2]> x[i:i+k-1]
[1] 0

So, it didnotconfirm. Let’s check that we have the correct subscript
range, which should be 1:2. Is it?

Browse[2]> i:i+k-1
[1] 2

Also wrong. Well, how aboutiandk? They should be 1 and 2, respec-
tively. Are they?

Browse[2]> i
[1] 1
Browse[2]> k
[1] 2

Well, those do confirm. Thus, our problem must be with the expression
i:i+k-1. After some thought, we realize there is an operator precedence
problem there, and we correct it toi:(i+k-1).
Is it okay now?

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

No, as mentioned, it should be (4,7,8).
Let’s set a breakpoint inside the loop and take a closer look.

> setBreakpoint("findruns.R",5)
/home/nm/findruns.R#5:
findruns step 4,4,2 in <environment: R_GlobalEnv>
> findruns(c(1,0,0,1,1,0,1,1,1),2)
findruns.R#5
Called from: eval(expr, envir, enclos)
Browse[1]> x[i:(i+k-1)]
[1]10

Good, we’re dealing with the first two elements of the vector, so our bug
fix is working so far. Let’s look at the second iteration of the loop.

Browse[1]> c
findruns.R#5
Called from: eval(expr, envir, enclos)

294 Chapter 13

Free download pdf