30  R: debug/undebug

30.1 Console

  • The debug function set, unset or query the debugging flag on a function.

  • When a function flagged for debugging is entered, normal execution is suspended and the body of function is executed one statement at a time.

  • Check ?debug for further details.

  • Relevant functions are: debug(function_name), undebug(function_name), debugonce(function_name)

30.2 Run in debug mode

  • In the console, type debug(fn_Mean)

  • Run the function as shown below

  • Once in the browser mode, move around using the standard options n, s, f, c, Q etc.

  • After the completion of operation, type undebug(fn_Mean) to undebug.

  • If you debugonce(fn_Mean), no need to run undebug(fn_Mean)

30.3 RStudio

  • In the RStudio environment, you can use traceback, run following function call that throws error

  • Select: Debug > On Error > Error Inspector

  • Run the following function and explore Rerun with Debug

  • RStudio also provides many useful details through Environment and Traceback panes.

30.4 Browser window option

  • In the Debug mode of browser window, you can move around the function using n, s, f, c, Q etc.

  • If you have a variable names as n, s, f, c, Q, then use print(variable_name)

  • You can also use other standard R commands to explore the objects in the function environment.

Code
X = c(NA, 12, 0, "A", 18)
fn_Mean(X, na.rm = TRUE)


You can also debug a function and investigate each step of the execution, even if the function does not run into any errors.

Code
X = c(NA, 12, -15, 14, 18)
fn_Mean(X, na.rm = TRUE)