debug, undebug

Use debug to put a function into debugging mode. When a function is in debugging mode, the function’s commands are run one at a time, and the function only moves onto the next command when told to do so. Between each of these function commands, the variables within the function are accessible and other commands may be run, making it easy to check the values of variables, change those values, or run other commands. To take a function out of debugging mode, use the undebug function.
debug(fun)
  • fun – A function.
undebug(fun)
  • fun – A function.

Example. Below is a function that performs three actions then returns the x3 object. While there aren’t errors in this function, we can use debug to peer inside, explore variables, and even change the values of variables while the function runs. To highlight how easy it is to change the values of variables, I altered the value of x3 right before its value was returned from the function (hence the output of “hello”). Finally, don’t forget to undebug the function.
> sqAdd5ThenSqrt <- function(x){
+   x1 <- x^2
+   x2 <- x1+5
+   x3 <- sqrt(x2)
+   return(x3)
+ }
> 
> sqAdd5ThenSqrt(5)
[1] 5.477226
> 
> debug(sqAdd5ThenSqrt)
> sqAdd5ThenSqrt(5)
debugging in: sqAdd5ThenSqrt(5)
debug: {
    x1 <- x^2
    x2 <- x1 + 5
    x3 <- sqrt(x2)
    return(x3)
}
Browse[2]> 
debug: x1 <- x^2
Browse[2]> x1 # line above hasn't been run yet
Error: object 'x1' not found
Browse[2]> 
debug: x2 <- x1 + 5
Browse[2]> x1
[1] 25
Browse[2]> 
debug: x3 <- sqrt(x2)
Browse[2]> x2
[1] 30
Browse[2]> 
debug: return(x3)
Browse[2]> x3
[1] 5.477226
Browse[2]> x3 <- "hello"
Browse[2]> 
exiting from: sqAdd5ThenSqrt(5)
[1] "hello"
> 
> undebug(sqAdd5ThenSqrt)
> sqAdd5ThenSqrt(5)
[1] 5.477226
Tip. When in debugging mode, notice that commands are shown before they are run. While a little confusing at first, this makes it easy to know what’s coming next and check variables in a command before it is run.

Leave a Reply