---
author: "Victòria Agudetse"
date: "04/07/2024"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteEngine{knitr::knitr}
  %\VignetteIndexEntry{The browser() function}
  %\usepackage[utf8]{inputenc}
---

The browser() function
-----------------------------------------

> NOTE: This vignette was used as an Ice-Breaker of the R User Meeting held at BSC on July 4th, 2024.

The `browser()` function is a very useful tool for debugging in R because it allows us to "browse" (inspect) an environment when we run the code in the terminal or an IDE like RStudio.
It acts as a "breakpoint" in the code. For example, we can use it inside a function:

```r
fun <- function(x) {
  x <- x + 20
  y <- mean(x)
  browser() # inspect the function environment here
  return(y)
}

data <- array(1:10)
# Let's check the original data
data
# [1]  1  2  3  4  5  6  7  8  9 10

# If we call the function, the browser will open when it reaches that line in the code:
result <- fun(x = data)
# Called from: fun(x = data)
# We can see the value of x and y inside the fun environment
# Browse[1]> x
# [1] 21 22 23 24 25 26 27 28 29 30
# Browse[1]> y
# [1] 25.5
# Browse[1]> f # exit browser and continue the execution
```

We can also add conditions to the browser() call using the `expr` parameter. For example, adding a debug flag to the function:

```r
# For example, we could add a debug flag to the function:
fun <- function(x, debug = FALSE) {
  x <- x + 20
  y <- mean(x)
  browser(expr = {debug}) # Activate only if debug is TRUE
}

fun(x = data)
fun(x = data, debug = TRUE)

# Or activating the browser inside a loop only when a condition is met:
j <- 0
for (i in 1:10) {
  j <- i + j
  browser(expr = {i == 2}) # Activate only when i is 2
}
```

Several commands can be used inside the browser environment to navigate it. Some useful ones:
- `c`: exit the browser and continue execution at the next statement.
- `f`: finish execution of the current loop or function.
- `help`: print a list of all available browser commands.
- `where`: print a stack trace of all active function calls.
- `Q`: exit the browser and top-level prompt.
