R Language Debugging Using browser

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The browser function can be used like a breakpoint: code execution will pause at the point it is called. Then user can then inspect variable values, execute arbitrary R code and step through the code line by line.

Once browser() is hit in the code the interactive interpreter will start. Any R code can be run as normal, and in addition the following commands are present,

CommandMeaning
cExit browser and continue program
fFinish current loop or function \
nStep Over (evaluate next statement, stepping over function calls)
sStep Into (evaluate next statement, stepping into function calls)
wherePrint stack trace
rInvoke "resume" restart
QExit browser and quit

For example we might have a script like,

toDebug <- function() {
    a = 1
    b = 2
    
    browser()
    
    for(i in 1:100) {
        a = a * b
    }
}

toDebug()

When running the above script we initially see something like,

Called from: toDebug
Browser[1]>

We could then interact with the prompt as so,

Called from: toDebug
Browser[1]> a
[1] 1
Browser[1]> b
[1] 2
Browse[1]> n
debug at #7: for (i in 1:100) {
    a = a * b
}
Browse[2]> n
debug at #8: a = a * b
Browse[2]> a
[1] 1
Browse[2]> n
debug at #8: a = a * b
Browse[2]> a
[1] 2
Browse[2]> Q

browser() can also be used as part of a functional chain, like so:

mtcars %>% group_by(cyl) %>% {browser()}


Got any R Language Question?