How to Step Through Debugging an R Function - dummies

How to Step Through Debugging an R Function

You can step through a function after you tell R you want to debug it using the debug() function. From then on, R will switch to the browser mode every time that function is called from anywhere in R, until you tell R explicitly to stop debugging or until you overwrite the function by sourcing it again.

To turn on stepping through the debug of the function, use debug(logit)

To stop debugging a function, you simply use undebug(logit).

If you want to step through a function only once, you can use the function debugonce() instead of debug(). R will go to browser mode the next time the function is called, and only that time — so you don’t need to use undebug() to stop debugging.

If you try the function logitpercent() again after running the code debug(logit), you see the following:

> logitpercent('50%')
debugging in: logit(as.numeric(x))
debug at D:/RForDummies/Ch10/logitfunc.R#2: {
  x <- ifelse(x < 0 | x > 1, "NA", x)
  log(x/(1 - x))

You see that the prompt changed. It now says Browse[2]. This prompt tells you that you’re browsing inside a function.

The number indicates at which level of the call stack you’re browsing at that moment. Remember from the output of the traceback() function that the logit() function occurred as the second function on the call stack. That’s the number 2 in the output above.

The additional text above the changed prompt gives you the following information:

  • The line from where you called the function — in this case, the line logit(as.numeric(x)) from the logitpercent() function

  • The file or function that you debug — in this case, the file logitfunc.R, starting at the second line

  • Part of the code you’re about to browse through