Any­one who starts writ­ing seri­ous R code (i.e., code that involves user-written func­tions) soon finds the need to use debug­ging tools. There are a few basic tools in R that are worth know­ing about.

The func­tion debug() allows one to step through the exe­cu­tion of a func­tion, line by line. At any point, you can print out val­ues of vari­ables or pro­duce a graph of the results within the func­tion. While debug­ging, you can sim­ply type “c” to con­tinue to the end of the cur­rent sec­tion of code (e.g., to the end of a for loop, or the end of the func­tion itself).

The func­tion browser() stops the exe­cu­tion of a func­tion until the user allows it to con­tinue. This is use­ful if you don’t want to step through all the code, line-by-line, but you want it to stop at a cer­tain point so you can check out what is going on.

If your code has already crashed and you want to know where the offend­ing line is, try traceback(). This will (some­times) show where abouts in the code the prob­lem occurred.

Check out the help files for the above func­tions for the details.

Dun­can Mur­doch also has an excel­lent debug­ging page on the web: Debug­ging in R which con­tains a wealth of extremely help­ful information.

  • Share/Bookmark