```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, comment = NA, collapse = TRUE)
```

## Bugs!

1. Crash: function call exits with error

2. Incorrect behavior

3. Unexpected behavior


```{r, error = TRUE}
library(MASS)
data(Pima.te)

## Crash
subset( head(Pima.te), npreg > a )

## Incorrect behavior
subset( head(Pima.te), type = "yes" & npreg > 2 )

## Unexpected behavior
subset( head(Pima.te), type == "yes" & npreg > 2 )
```

## Tools

`traceback` to find where error occurred: 

```{r, eval = FALSE}
library(MASS)
data(Pima.te)
subset(Pima.te, npreg > a)
traceback()
```

 `debug` to execute code line by line:
 
* `debug(<function-name>)` to start debugging
* At debug-prompt:

    - `n` or Enter to execute current line, continue to next
    - `c` to run function from the current line to end
    - `Q` to quit
    - any variable, expression is evaluated in the current environment 
 
 * `undebug(<function-name>)` to retore normal behavior

`browser` to set stop points when running code:

* Add `browser()` command to code at strategic locations
* Function will execute to browser and open debugger as above 

Rstudio `Debug` menu: similar fucntionality, but can only be started for R scripts

## Example

```{r}
f1 = function(x, y, flag = TRUE, n = 1000) 
{
  if ( missing(y) ) 
  {
    if (flag | (x > 0)) y = abs(x)
  }
  g = function(z) z + x
  acc = 0
  ## What happened to ?cumsum 
  for (i in 1:1000) acc = acc + runif(1) 
  g(y)
}
```

Run tests:

```{r, eval = FALSE}
f1(1)
f1(-1)
f1(1, flag = FALSE)
f1(-1, flag = FALSE)
```

1. Run `traceback` (not very useful)

2. Use `debug` to run the critical case line-by-line as far as practical 

3. Note how the focus jumps between editor and console; editor has some decent `Debug` menu items, but inspection of local vars (e.g. `ls()`) is in the console

4. Add a `browser()` statement that allows you to pass over the loop (or use the menu item)

3. Fix the function, remove the `browser` if necessary & `undebug`


## Minimal replicable example

Simplify any example that generates an error

Smallest self-contained set of data & code that generates the error reliably

- Often finds the problem
- Easier to read & understand on Stackoverflow etc.
- Shows respect for other people's time

## Exercise: nestedCC

Small package `nestedCC` on [github.com/alexploner/nestedCC](https://github.com/alexploner/nestedCC)

0. Reminder: nested case-control studies?
1. Use menu `New project` to clone the repository locally
2. Load the package, and run `example(nestedCC)` to see how the function works
4. Look at the small example data set `cohort_test` in the package
5. Run the command
```r
nestedCC(cohort_test, event = "event", exit = "time", match = "sex", seed=41)
```

Look closely at the results, and try to find the error. As the code is not totally obvious, step slowly through it using `debug`, to understand what is happening.

Solution: branch `fix_sample` in the repository has a fixed version of the function.

