Debugging in R Programming
Debugging is a process of cleaning a program code from bugs to run it successfully. While writing codes, some mistakes or problems automatically appears after the compilation of code and are harder to diagnose. So, fixing it takes a lot of time and after multiple levels of calls.
Debugging in R is through warnings, messages, and errors. Debugging in R means debugging functions. Various debugging functions are:
- Editor breakpoint
Editor Breakpoints can be added in RStudio by clicking to the left of the line in RStudio or pressing Shift+F9 with the cursor on your line. A breakpoint is same as browser() but it doesn’t involve changing codes. Breakpoints are denoted by a red circle on the left side, indicating that debug mode will be entered at this line after the source is run.
traceback() function is used to give all the information on how your function arrived at an error. It will display all the functions called before the error arrived called the “call stack” in many languages, R favors calling traceback.
2: function_1(b) at #1 1: function_2("s")
traceback() function displays the error during evaluations. The call stack is read from the function that was run(at the bottom) to the function that was running(at the top). Also we can use
traceback() as an error handler which will display error immediately without calling of traceback.
Error in a + 5 : non-numeric argument to binary operator 2: function_1(b) at #1 1: function_2("s")
browser() function is inserted into functions to open R interactive debugger. It will stop the execution of function() and you can examine the function with the environment of itself. In debug mode, we can modify objects, look at the objects in the current environment, and also continue executing.
browser> command in consoles confirms that you are in debug mode. Some commands to follow:
- ls(): Objects available in current environment.
- print(): To evaluate objects.
- n: To examine the next statement.
- s: To examine the next statement by stepping into function calls.
- where: To print a stack trace.
- c: To leave debugger and continue with execution.
- C: To exit debugger and go back to R prompt.
debug() statement automatically inserts
browser() statement at the beginning of the function.
recover() statement is used as an error handler and not like the direct statement. In
recover(), R prints the whole call stack and lets you select which function browser you would like to enter. Then debugging session starts at the selected location.
Enter a frame number, or 0 to exit 1: function_2("s") 2: #2: function_1(b) Selection:
The debugging session starts at the selected location.
Please Login to comment...